[英]How to detect Cell selection in UITableView - Swift
just wondering how I would go about implementing didSelectRowAtIndexPath or something similar into my app.只是想知道我将如何在我的应用程序中实现 didSelectRowAtIndexPath 或类似的东西。 I have a populated Table View with several dynamic cells and basically I want to change Views once a certain cell is selected.我有一个包含多个动态单元格的填充表视图,基本上我想在选择某个单元格后更改视图。
I am able to get my head around it in Obj-C, but there is nothing on google to help me with Swift!我可以在 Obj-C 中了解它,但是谷歌上没有任何东西可以帮助我使用 Swift! Any help would be appreciated as I am still learning任何帮助将不胜感激,因为我仍在学习
You can use didSelectRowAtIndexPath
in Swift.您可以在 Swift 中使用didSelectRowAtIndexPath
。
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
NSLog("You selected cell number: \(indexPath.row)!")
self.performSegueWithIdentifier("yourIdentifier", sender: self)
}
For Swift 3 it's对于 Swift 3,它是
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
NSLog("You selected cell number: \(indexPath.row)!")
self.performSegueWithIdentifier("yourIdentifier", sender: self)
}
Just make sure you implement the UITableViewDelegate
.只要确保你实现了UITableViewDelegate
。
This is how I managed to segue from UITableView cells to other view controllers after implementing cellForRow, numberOfRowsInSection & numberOfSectionsInTable.这就是我在实现 cellForRow、numberOfRowsInSection 和 numberOfSectionsInTable 后设法从 UITableView 单元格转到其他视图控制器的方式。
//to grab a row, update your did select row at index path method to:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
NSLog("You selected cell number: \(indexPath.row)!");
if indexPath.row == 1 {
//THE SEGUE
self.performSegue(withIdentifier: "goToMainUI", sender: self)
}
}
Will output: You selected cell number: \\(indexPath.row)!
将输出: You selected cell number: \\(indexPath.row)!
Remember to match the identifier of your segue in story board to the identifier in the function, eg goToMainUI
.请记住将故事板中的 segue 标识符与函数中的标识符相匹配,例如goToMainUI
。
Use the following code to select cell at '0' index programmatically for collectionView.使用以下代码以编程方式为 collectionView 选择索引为 '0' 的单元格。
self.collectionView.reloadData()
DispatchQueue.main.async {
self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.