ios 如何检测 UITableView 中的单元格选择 - Swift

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28430232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:46:57  来源:igfitidea点击:

How to detect Cell selection in UITableView - Swift

iosswiftuitableviewios8uikit

提问by Alex

just wondering how I would go about implementing didSelectRowAtIndexPath or something similar into my app. I have a populated Table View with several dynamic cells and basically I want to change Views once a certain cell is selected.

只是想知道我将如何在我的应用程序中实现 didSelectRowAtIndexPath 或类似的东西。我有一个包含多个动态单元格的填充表视图,基本上我想在选择某个单元格后更改视图。

I am able to get my head around it in Obj-C, but there is nothing on google to help me with Swift! Any help would be appreciated as I am still learning

我可以在 Obj-C 中了解它,但是谷歌上没有任何东西可以帮助我使用 Swift!任何帮助将不胜感激,因为我仍在学习

回答by Christian

You can use didSelectRowAtIndexPathin Swift.

您可以didSelectRowAtIndexPath在 Swift 中使用。

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.

回答by WHC

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, e.g goToMainUI.

请记住将故事板中的 segue 标识符与函数中的标识符相匹配,例如goToMainUI.

回答by Asad Jamil

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))
}