[英]How to have tableview and searchbar selection sync in Swift?
我有一个约有200个项目的表格视图,允许用户进行多个选择,然后用户提交他们的选择。
我想在该tableview的标题中有一个搜索栏,这将使选择过程更加容易。
我可以让搜索结果表具有多个选择,但是当用户选择并删除其他选择的查询时,由于两个都是不同的表,因此它们与表视图不同步。
如何使用搜索功能实现多选表视图。
例子-
我有带有以下数据的表视图-
__ Hello
__ Hello World
__ hi There
__ What's Up
__ iOS 9 dev
__ Swift
__ Hey there
我想要这样的东西,当用户在搜索栏中输入“ sw”并选择Swift并删除搜索查询以执行另一次搜索时。
__ Hello
__ Hello World
__ hi There
__ What's Up
__ iOS 9 dev
√ Swift
__ Hey there
现在,如果他/她输入“ wh”并选择“最新动态”,则表视图选择应为
__ Hello
__ Hello World
__ hi There
√ What's Up
__ iOS 9 dev
√ Swift
__ Hey there
当用户点击提交按钮时,选择数组应返回为[3,5]
有人可以帮忙吗?
我是Swift和iOS开发的新手,我们将不胜感激。
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
@IBOutlet var tableView: UITableView!
@IBOutlet var searchBar : UISearchBar!
// third field in array is your index, everything more easy with it
var array = [["Swift", false, 0], ["teste", false, 1], ["linguagem", false, 2], ["objectivec", false, 3]]
var arrayFilter = []
@IBOutlet weak var okbutton: UIButton!
@IBAction func okButton(sender: AnyObject) {
var selection : [Int] = []
for element in self.array {
if element[1] as! Bool {
selection.append(element[2] as! Int)
}
}
print(selection)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
// filter array with string that start with searchText
self.arrayFilter = array.filter{
if let pos = ($0[0] as! String).lowercaseString.rangeOfString(searchText.lowercaseString) {
return (pos.startIndex == ($0[0] as! String).startIndex)
}
return false
}
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.searchBar.text == "" ? self.array.count : self.arrayFilter.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let lista = self.searchBar.text == "" ? self.array : self.arrayFilter
cell.textLabel?.text = lista[indexPath.row][0] as? String
// check cell based on second field
cell.accessoryType = lista[indexPath.row][1] as! Bool ? .Checkmark : .None
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let lista = self.searchBar.text == "" ? self.array : self.arrayFilter
let id = lista[indexPath.row][2] as! Int
// invert the value of checked
self.array[id][1] = !(array[id][1] as! Bool)
self.searchBar.text = ""
tableView.reloadData()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.