Swift 中使用闭包实现单行 UITableView 创建
将 BlockTableView.swift
复制并粘贴到您的项目中。
let table = BlockTableView (frame: self.view.frame,
numberOfRowsInSection: { (section) -> Int in
return dataSource.count
},
cellForRowAtIndexPath: { (tableView, indexPath) -> UITableViewCell in
var cell = UITableViewCell (style: .Default, reuseIdentifier: "Identifer")
let current = dataSource[indexPath.row]
cell.textLabel.text = current
return cell
},
didSelectRowAtIndexPath: { (tableView, indexPath) -> () in
let selected = dataSource[indexPath.row]
println("\(selected) selected")
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
)
convenience init(frame: CGRect,
numberOfRowsInSection : (section: Int) -> Int,
cellForRowAtIndexPath : (tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell,
didSelectRowAtIndexPath : (tableView: UITableView, indexPath: NSIndexPath) -> ())
convenience init(frame: CGRect,
numberOfSections : Int,
titleForHeaderInSection : (section: Int) -> String,
numberOfRowsInSection : (section: Int) -> Int,
cellForRowAtIndexPath : (tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell,
didSelectRowAtIndexPath : (tableView: UITableView, indexPath: NSIndexPath) -> ())
convenience init(frame: CGRect,
registeredCells : [String: AnyClass],
numberOfRowsInSection : (section: Int) -> Int,
cellForRowAtIndexPath : (tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell,
didSelectRowAtIndexPath : (tableView: UITableView, indexPath: NSIndexPath) -> ())
init(frame: CGRect,
registeredCells : [String: AnyClass]?,
numberOfSections : Int?,
titleForHeaderInSection : ((section: Int) -> String)?,
numberOfRowsInSection : (section: Int) -> Int,
cellForRowAtIndexPath : (tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell,
didSelectRowAtIndexPath : (tableView: UITableView, indexPath: NSIndexPath) -> ())
UITableViewDelegate
/UITableViewDataSource
方法来轻松添加更多初始化器搜索栏实现从未如此简单
func addSearchBar (searchResultTableView tableView: BlockTableView, didSearch: (String)->())
只需创建另一个用于显示结果的 BlockTableView
,并在 didSearch
中实现过滤或搜索功能,例如
var filtered: [String]! // search result dataSource
table.addSearchBar(searchResultTableView:
BlockTableView (frame: self.view.frame,
numberOfRowsInSection: { (section) -> Int in
return filtered.count
},
cellForRowAtIndexPath: { (tableView, indexPath) -> UITableViewCell in
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = filtered[indexPath.row]
return cell
},
didSelectRowAtIndexPath: { (tableView, indexPath) -> () in
return
}
), didSearch: { searchText in
filtered = filter (dataSource) { $0.rangeOfString(searchText) != nil }
}
)