检测在 tableview 中按下的 uibutton:Swift 最佳实践 [英] detecting uibutton pressed in tableview: Swift Best Practices

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

问题描述

我有一个表格视图,其中包含可变数量的单元格,代表与其特定教师相对应的学生.它们是自定义单元格,带有一个按钮,可以触发新 VC 的转场,显示该单元格所在学生的详细信息.我的问题是:

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

推荐答案

如果你的代码允许,我建议你设置 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 答案的 Swift 翻译:

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 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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