Created
March 17, 2012 15:30
-
-
Save minhnc/2061218 to your computer and use it in GitHub Desktop.
TableView - Custom SearchBar: Prefix Search, Customize No Result
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var win = Ti.UI.createWindow({backgroundColor: 'white'}); | |
var searchbar = Ti.UI.createSearchBar({ top: 0, height: 43, showCancel: false }); | |
win.add(searchbar); | |
// Function to dump data | |
function dumpData() { | |
var data = []; | |
for(var i = 0; i < 20; i ++) { | |
data.push({title: Math.random().toString(36).substring(5)}); | |
} | |
return data; | |
} | |
var data = dumpData(); | |
var tbl = Ti.UI.createTableView({ | |
data: data, | |
top: searchbar.height | |
}); | |
win.add(tbl); | |
win.open(); | |
// This will do the trick :) | |
searchbar.addEventListener('change', function(e){ | |
tbl.setData([]); | |
var searchResults = mysearch(e.value, data); | |
if (searchResults.length == 0) {// "No Result" | |
tbl.setData([ | |
{title: ''}, | |
{title: ''}, | |
{title: 'No Result'}, | |
]); | |
} else { | |
tbl.setData( searchResults ); | |
} | |
}); | |
searchbar.addEventListener('return', function(e){ | |
searchbar.blur(); | |
}); | |
tbl.addEventListener('click', function(e) { | |
searchbar.blur(); | |
}); | |
// You can customize to whatever search algorithm you want | |
function mysearch(value, data) { | |
var searchResults = []; | |
for(var i = 0, len = data.length; i < len; i ++) { | |
if (data[i].title.indexOf(value) != -1) { | |
searchResults.push(data[i]); | |
} | |
} | |
return searchResults; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment