ios 当用户快速点击一个单元格时触发一个动作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26652819/
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 03:25:59  来源:igfitidea点击:

Trigger an action when an user clicks on a cell in swift

iosuitableviewswift

提问by soling

I'm creating an app using Swift. I have an UITableViewthat I populate with some data from a database. When user clicks on a cell, I would like to trigger an action.

我正在使用 Swift 创建一个应用程序。我有一个UITableView我用数据库中的一些数据填充的。当用户点击一个单元格时,我想触发一个动作。

What I have done :

我做了什么 :

var array: [String] = ["example"]


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }



    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell(style :UITableViewCellStyle.Default, reuseIdentifier: "cell")
        cell.textLabel.text = array[indexPath.row]
        cell.tag = indexPath.row
        cell.targetForAction("getAction:", withSender: self)
        return cell
    }

    func getAction(sender:UITableViewCell)->Void {
        if(sender.tag == 0) {
            println("it worked")
        }
    }

I tried to adapt a solution from an another post but I did it definitely wrong. Thank you in advance

我试图从另一篇文章中改编一个解决方案,但我做错了。先感谢您

回答by Rajeev Bhatia

Implement UITableViewDelegateand use didSelectRowAtIndexPath

实施UITableViewDelegate和使用didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

you can use the indexPathto get the item from your collection and perform your action

您可以使用indexPath来从您的收藏中获取项目并执行您的操作

回答by Luan Nico

In Swift 4, I believe the method has changed ever so slightly:

在 Swift 4 中,我相信该方法已经发生了微小的变化:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // your code
}