【问题标题】:How to detect cell selection in UITableView in Swift?如何在 Swift 中检测 UITableView 中的单元格选择?
【发布时间】:2015-04-10 09:36:31
【问题描述】:

如何在我的 Swift 应用中实现 didSelectRowAtIndexPath: 或类似的东西?

我有一个包含多个动态单元格的填充表格视图,我想在选择某个单元格后更改视图。

我可以在 Objective-C 中理解它,但在 Swift 上没有任何东西可以帮助我!

【问题讨论】:

    标签: ios swift uitableview uikit


    【解决方案1】:

    你可以在 Swift 中使用didSelectRowAtIndexPath

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        NSLog("You selected cell number: \(indexPath.row)!")
        self.performSegueWithIdentifier("yourIdentifier", sender: self)
    }
    

    只要确保你实现了UITableViewDelegate

    【讨论】:

    • 非常感谢!谷歌根本没有,我花了很长时间寻找和尝试自己……但这给我带来了另一个问题。如何确保每个单独的单元格执行不同的转场?
    • 检查 indexPath.row。它为您提供行号。然后你可以使用 if-else。
    • 太棒了!谢谢你的帮助,我现在终于开始更好地理解 Swift 了 :)
    • 我建议你从 raywenderlich.com 阅读一些 tableview-tutorials
    • 这是正确的代码吗? override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { NSLog("You selected cell number: \(indexPath.row)!") if indexPath.row == 0 { self.performSegueWithIdentifier("MoveToSignIn", sender: self) }
    【解决方案2】:

    这就是我在实现 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)
        }
    }
    

    将输出:You selected cell number: \(indexPath.row)!

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

    【讨论】:

      【解决方案3】:

      使用以下代码以编程方式为 collectionView 选择索引为“0”的单元格。

      self.collectionView.reloadData()
      DispatchQueue.main.async {
        self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-20
        • 1970-01-01
        • 2011-05-18
        • 2015-05-31
        • 1970-01-01
        • 2020-03-24
        • 2012-09-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多