我想要自动完成的文本框,例如如果我按A,它应该显示相关的单词,如苹果,飞机等。我想做类似的Google搜索。是否在iOS和Android上的Titanium上有类似此操作的控件。帮助示例代码或它钛不可能?

最佳答案

以下代码将为您工作。尝试一下,然后根据需要进行修改。在这里,我使用array(searchArray)作为数据存储(您可以根据需要将其替换为数据库字段或源)。

//Table view showing your autocomplete values
var tblvAutoComplete = Ti.UI.createTableView({
    width           : '100%',
    backgroundColor : '#EFEFEF',
    height          : 0,
    maxRowHeight    : 35,
    minRowHeight    : 35,
    allowSelection  : true
});
//Starts auto complete
txtAutoComplete.addEventListener('change', function(e){
    var pattern = e.source.value;
    var tempArray = PatternMatch(searchArray, pattern);
    CreateAutoCompleteList(tempArray);
});
//You got the required value and you clicks the word
tblvAutoComplete.addEventListener('click', function(e){
    txtAutoComplete.value = e.rowData.result;
});

//Returns the array which contains a match with the pattern
function PatternMatch(arrayToSearch, pattern){
    var searchLen = pattern.length;
    arrayToSearch.sort();
    var tempArray = [];
    for(var index = 0, len = arrayToSearch.length; index< len; index++){
        if(arrayToSearch[index].substring(0,searchLen).toUpperCase() === pattern.toUpperCase()){
            tempArray.push(arrayToSearch[index]);
        }
    }
    return tempArray;
}
//setting the tableview values
function CreateAutoCompleteList(searchResults){
    var tableData = [];
    for(var index=0, len = searchResults.length; index < len; index++){

            var lblSearchResult = Ti.UI.createLabel({
                top            : 2,
                width          : '40%',
                height         : 34,
                left           : '5%',
                font           : { fontSize : 14 },
                color          : '#000000',
                text           : searchResults[index]
            });

            //Creating the table view row
            var row = Ti.UI.createTableViewRow({
               backgroundColor : 'transparent',
               focusable       : true,
               height          : 50,
               result          : searchResults[index]
            });

            row.add(lblSearchResult);
            tableData.push(row);
    }
    tblvAutoComplete.setData(tableData);
    tblvAutoComplete.height = tableData.length * 35;
}

这段代码在ios和android中都对我有用。希望您的问题得到解决:D

10-08 17:57