빠른 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
}
}
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 })
한 번 작동하는 이유는 그 시간에도 내 테이블보기에서 검색 할 수 없습니다. 이제 갑자기이 오류가 발생합니다.
테이블보기에서 검색 컨트롤러를 구현했습니다. 검색된 데이터를 필터링하고 일치하는 문자열로 배열을 만드는 기능을 제공합니다.
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 함수에서 검색 컨트롤러가 활성화되어 있는지 확인하고 채운 배열에서 데이터를 제공하지 않으면 기본 배열을 사용하는지 확인합니다. 또한 검색 컨트롤러가 활성화되어 있는지 확인하여 행 수를 설정해야합니다. 활성화 된 경우 채워진 배열 수를 반환하고 그렇지 않으면 기본 배열 수를 반환하여 앱이 충돌하지 않도록합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다