[英]Can't get didSelectRowAt to work for TableView
我在讓didSelectRowAt
方法為常規ViewController
內的TableView
工作時遇到麻煩。 我已經確保在ViewController
代碼中設置了表的delegate
和data source
。 此ViewController
使用搜索查詢到API的結果填充表tableview
單元格,並且單元格數據的呈現工作正常。
只是didSelectRowAt
方法沒有注冊。 我確實嘗試在Main.storyboard上手動添加相同的委托人信息,但是帶小號+
標記不會觸發任何彈出窗口。 我想知道Main.storyboard
是否需要修復。 我還附加了ViewController
和TableView
連接檢查器的圖像。 我是iOS開發的新手,沒有用於移動設計的圖形界面的豐富經驗,因此我認為它確實存在,但也許我錯了。
這是我的代碼的基本版本:
class SearchViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet var searchBar: UISearchBar!
...variable declarations ....
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
searchResults = []
searchBar.delegate = self
tableView.dataSource = self
tableView.delegate = self
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults!.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchTableViewCell", for: indexPath) as! SearchTableViewCell
if(searchActive && !(self.searchResults?.isEmpty)!) {
(doing some stuff with search results here...works fine)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("hello!")
}
func searchBar(_ searchBar: UISearchBar,
textDidChange searchText: String) {
print("search text \(searchText)")
getSearchResultJSON(term: searchText) { json in
let data = json as! [Dictionary<String, String>]
self.searchResults = data
}
self.tableView.reloadData()
}
...
}
[ ]
[ ]
編輯:作為一個健全性檢查,如果搜索異步功能是否有任何更改,我只是嘗試刪除所有與搜索相關的代碼,並從硬編碼的虛擬變量數組填充tableview。 它可以顯示虛擬變量,但仍然無法選擇單元格並獲得任何反應。 我還看到有幾條提到我以前使用didDeSelectRowAt而不是didSelectRow鍵入錯誤,該錯誤已得到解決,但行為是相同的。
這最終與我編寫的hideKeyboardWhenTappedAround()擴展中發生的輕擊手勢有關
您正在使用didDeselectRowAt
而不是didSelectRowAt
編輯
好吧,然后使用下面的委托
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
並使您的控制器符合UIGestureRecognizerDelegate
找到了! 罪魁禍首是self.hideKeyboardWhenTappedAround()
,這是我寫來隱藏鍵盤的擴展名。 這確實干擾了單元格的點擊,因為它確實利用了UITapGestureRecognizer
。 謝謝大家的提示。
如果您在主視圖上使用輕擊手勢,則表視圖單元格的select方法無法正常工作。
在您上載的圖片中,委托和數據源未連接到ViewController。 刪除viewdidload中的代碼(tableview.delegate = self)並將其連接到情節提要中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.