1
我無法用我的表定義單元格。它允許用戶搜索一個城市,這是給我帶來麻煩的代碼。這是視圖控制器的完整代碼。目標是允許用戶在其列表中搜索城市。Swift錯誤線程1:EXC_BAD_INSTRUCTION單元格定義
import UIKit
import Foundation
import CoreData
class SearchBar: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate{
var searchActive : Bool = false
var data: [String] = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"]
var filtered: [String] = []
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var checkavailability: UIBarButtonItem!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var addselected: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
/* Setup delegates */
tableView.delegate = self
tableView.dataSource = self
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 = data.filter({ (text) -> Bool in
let tmp: NSString = text
let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
return range.location != NSNotFound
})
if(filtered.count == 0){
searchActive = false;
}
else {
searchActive = true;
}
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
}
else {
return data.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell!
if(searchActive == true){
cell.textLabel?.text = filtered[indexPath.row]
}
else {
cell.textLabel?.text = data[indexPath.row] \\ this is where the error comes up
}
return cell
}
}
當我這樣做時,我得到了else語句中的錯誤。同樣的確切的一個。 –
@SaiKappagantula,你的代碼中有'filtered'和'data'是什麼?你沒有在你的問題中包含聲明它們的代碼,所以我們沒有辦法幫助你。就我們所知,數據和過濾是未聲明或未初始化的變量。 – akshay
其他事項: - 將'let'更改爲'var',因爲您修改它, - 檢查tableView.dequeue是否返回nil。您必須爲tableView定義「cell」類型的第一個單元格。你可以通過編程方式檢查nil,然後在這裏準備這樣一個單元,或者在Interface Builder中(如果你使用它來編寫這個應用程序) –