完成UI部分後我門開始在ViewController.swift編寫代碼
首先
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
用於獲取前端的信息
對於信息的部分 這裏只用數組
var data = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"]
//filtered search result
var filtered:[String] = []
後面聲明的數組用來存放我們經過篩選的結果實現信息在tableView中的顯示
//make sure you how many sections you need for displaying items you have
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//you also need to let the tableView outlet from the storyboard know how many cells should be there
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
}
return data.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//we already have a original cell in storyboard and it has an identity as Cell
//we also know how many cells wen need the function: tableView
//dequeueReusableCellWithIdentifier just return a object whose type is cell and then we set the value in cell
//we get the value of indexPath from dataSource which we set in viewDidLoad
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
if(searchActive){
cell.textLabel?.text = filtered[indexPath.row]
} else {
cell.textLabel?.text = data[indexPath.row];
}
//do not forget to return a cell
return cell;
}
我的註釋應該還算詳細 這都是對tableView的protoCell操作的基本套路 切記要在storyBoard設置好tableView中protoCell與tableVIew函數中尋找的ID相同
然後我們需要一個函數來通過用戶的輸入過濾現有信息並獲取結果
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
filtered = data.filter({ (text) -> Bool in
//make a constant of NSString which text by users
let tmp: NSString = text
//rangeOfString will return the result strings which matches the user input
let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
return range.location != NSNotFound
})
//determine if no result found
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
//notice: Do not forget
//we need to update the information in the cells
self.tableView.reloadData()
}
首先用到的是data.filter 後面是一個閉包, 聲明一個臨時變量tmp用rangeOfString函數,關於這個篩選的部分swift提供了多個函數能夠對字符串進行篩選,這裏使用的函數不是帶有區域參數的函數,不適合於用戶級搜索,官方建議的是使用
public func rangeOfString(searchString: String, options mask: NSStringCompareOptions, range searchRange: NSRange, locale: NSLocale?) -> NSRange
下面是開發文檔中NSLocale的部分內容
public class NSLocale : NSObject, NSCopying, NSSecureCoding, NSCoding {
public func objectForKey(key: AnyObject) -> AnyObject?
public func displayNameForKey(key: AnyObject, value: AnyObject) -> String?
public init(localeIdentifier string: String)
public init?(coder aDecoder: NSCoder)
}
extension NSLocale {
public var localeIdentifier: String { get } // same as NSLocaleIdentifier
}
extension NSLocale {
@available(iOS 2.0, *)
public class func autoupdatingCurrentLocale() -> NSLocale // generally you should use this method
public class func currentLocale() -> NSLocale // an object representing the user's current locale
public class func systemLocale() -> NSLocale // the default generic root locale with little localization
}
不難看出能夠通過這個類輕鬆的設置所在地點,以便對於不同文字內容的輸入能夠及時辨識,從而不影響篩選功能
之後通過判斷filter中是否有結果來設置Bool值
var searchActive : Bool = false
最後的部分操作tableView重新加載數據
注意:
設置代理
override func viewDidLoad() {
super.viewDidLoad()
/* Setup delegates */
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
}
到此簡單的搜索功能就實現了