我正在使用swift 2.0。我已将搜索栏添加到表格视图中。我跑了两次,效果很好。但现在在我的代码中显示错误:
Cannot invoke 'filter' with an argument list of type '(@noescape (Element) throws -> Bool)'
当我尝试运行也无法搜索我的表格视图数据时,
这是我的完整代码:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate
{
var Table:NSArray = []
@IBOutlet weak var searchBar: UISearchBar!
var searchActive : Bool = false
var filtered:[String] = []
@IBOutlet weak var tableView: UITableView! // UITable view declaration
@IBOutlet weak var Resultcount: UILabel! // count label
let cellSpacingHeight: CGFloat = 5 // cell spacing from each cell in table view
var filteredTableData = [String]()
var resultSearchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
CallWebService() // call the json method
// nib for custom cell (table view)
let nib = UINib(nibName:"customCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
searchBar.delegate = self
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
filtered = Table.filter({ (text) -> Bool in
let tmp: NSString = text as! NSString
let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
return range.location != NSNotFound
})
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.tableView.reloadData()
}
// every time app quit and run, switch will be in off state
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(true)
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "PremiumUser")
}
func CallWebService()
{
let UrlApi = "url"
let Url = NSURL(string: UrlApi)
let Session = NSURLSession.sharedSession()
let Work = Session.dataTaskWithURL(Url!, completionHandler: { dataTask, response, error -> Void in
if (error != nil)
{
print(error)
}
var datos:NSData = NSData(data: dataTask!)
do {
let JsonWithDatos:AnyObject! = try NSJSONSerialization.JSONObjectWithData(datos, options: NSJSONReadingOptions.MutableContainers) as! NSArray
self.Table = JsonWithDatos as! NSArray
dispatch_async(dispatch_get_main_queue()) {
if (self.Table.count>0)
{
self.Resultcount.text = "\(self.Table.count) Results"
self.tableView.reloadData()
}
}
}catch{
print("Some error occured")
}
})
Work.resume()
}
// number of sections
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// number of rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
}
return self.Table.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:customCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! customCell
if(searchActive){
cell.vendorName.text = filtered[indexPath.row]
} else {
cell.vendorName.text = Table[indexPath.row] as! String;
}
let item = self.Table[indexPath.row] as! [String : String]
cell.vendorName.text = item["name"]
cell.vendorAddress.text = item["address"]
return cell
}
}
我在此行[{1}}
中的此方法func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
中收到错误
为什么它的工作一次,那个时候也无法在我的表视图中进行搜索。现在我突然收到这个错误。
答案 0 :(得分:1)
我在表格视图中实现了搜索控制器 我给你的功能是过滤搜索到的数据并创建一个匹配字符串的数组
func filterDestinations(searchString: String){
self.filteredDestinations.removeAll()
if(self.defaultarray.count > 0){
for obj in self.sortedDest{
if(obj.name!.rangeOfString(searchString, options: .CaseInsensitiveSearch, range: nil, locale: nil) != nil){
self.filteredDestinations.append(obj)
}
}
}
}// ends filterDestinations
之后你只需重新加载表视图,并在函数cellforrowatindex中检查如果搜索控制器处于活动状态而不是从填充数组中提供数据,否则使用默认数组。 你也必须通过检查搜索控制器是否有效来设置numberofrows。 如果它处于活动状态,则返回填充数组计数,否则返回默认数组计数,以便您的应用程序不会崩溃。
答案 1 :(得分:0)
只需删除closure参数和返回值类型即可。如果找不到字符串,rangeOfString
也会返回nil
。最好投射到Swift String
而不是NSString
。您正尝试将NSArray
(基本上[AnyObject]
分配给[String]
。您必须进行一些映射。
filtered = table.filter {
let tmp = $0 as! String
let range = tmp.rangeOfString(searchText, options: .CaseInsensitiveSearch)
return range != nil
}.map { $0 as! String }