在tableview中检测uibutton:Swift Best Practices [英] detecting uibutton pressed in tableview: Swift Best Practices

查看:128
本文介绍了在tableview中检测uibutton:Swift Best Practices的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个tableview,其中包含可变数量的单元格,表示与其特定教师相对应的学生。它们是具有按钮的自定义单元格,该按钮触发新VC的segue,提供有关其单元格的学生的详细信息。我的问题是:

I have a tableview with a variable number of cells representing students that correspond to their particular instructor. They are custom cells with a button that triggers a segue to a new VC, bringing up detailed information on the student whose cell it was. My question is:

swift中用于识别按下哪个按钮的最佳做法是什么?

What is the best practice in swift for identifying which button was pressed?

一旦我知道索引路径,我可以确定哪个学生的信息需要传递给下一个VC。在下面的帖子中,对于目标C有一个很好的答案,但我不确定如何转换为Swift。任何帮助将不胜感激。

Once i know the index path, I can identify which student's information needs to be passed to the next VC. There is a great answer for objective C in the post below, but I'm not sure how to translate to Swift. Any help would be much appreciated.

检测在UITableView中按下了哪个UIButton

Detecting which UIButton was pressed in a UITableView

推荐答案

如果您的代码允许,我' d建议您将 UIButton 标记设置为等于 indexPath.row ,因此当触发其操作时,您可以拉标记,因此在触发方法期间排出按钮数据。例如,在 cellForRowAtIndexPath 中,您可以设置标记:

If your code allows, I'd recommend you set the UIButton tag equal to the indexPath.row, so when its action is triggered, you can pull the tag and thus row out of the button data during the triggered method. For example, in cellForRowAtIndexPath you can set the tag:

button.tag = indexPath.row
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

然后在 buttonClicked:,你可以获取标签,从而获取行:

then in buttonClicked:, you can fetch the tag and thus the row:

func buttonClicked(sender:UIButton) {

    let buttonRow = sender.tag
}

否则,如果由于某种原因这不利于您的代码,则你链接到的这个Objective-C答案

Otherwise, if that isn't conducive to your code for some reason, the Swift translation of this Objective-C answer you linked to:

- (void)checkButtonTapped:(id)sender
{
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {
     ...
    }
}

是:

func checkButtonTapped(sender:AnyObject) {
      let buttonPosition = sender.convert(CGPoint.zero, to: self.tableView)
    let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
    if indexPath != nil {
        ...
    }
}

这篇关于在tableview中检测uibutton:Swift Best Practices的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆