swift - 从 TableViewCell 中的按钮执行 Segue

标签 swift tableview segue

我有一个带有按钮的 CustomCell 类。我正在使用原型(prototype)单元(不是 .xib)。我想让 tableviewcell 中的按钮执行 segue 并将值传递给新类。如何为 tableviewcell 中的按钮创建独特的操作?谢谢!

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    ...

    selectedAreaCode = areaCodes[indexPath.row]

    // Configure Cell
    cell.areaCodeButton.setTitle(areaCode, forState: UIControlState.Normal)


    cell.areaCodeButton.addTarget(self, action: "segue", forControlEvents: UIControlEvents.TouchUpInside)

    cell.selectionStyle = UITableViewCellSelectionStyle.None


    return cell
}

func segue() {

    self.performSegueWithIdentifier("toDialer", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if(segue.identifier == "toDialer") {

        let nextViewController = (segue.destinationViewController as! PhoneDialer)
        nextViewController.passedAreaCode = selectedAreaCode
    }
}

最佳答案

有很多方法可以从您的自定义单元格中获取点击操作,但我假设您正在尝试从 UIViewController 中检索操作,因为您正在尝试 segue。

因为您正在使一个单元格出队,所以您可以短暂地完全访问您的 cellForRowAtIndexPath 函数范围内的单元格。只要您将该按钮作为单元格的公共(public)属性,您就可以将该按钮的目标设置为您的 segue 方法。

此外,因为您要传递的内容在按钮本身的标题中,所以您只需从选择器访问发件人即可。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = yourCell()
    cell.button.addTarget(self, action: #selector(tap(:)), forControlEvents: .TouchUpInside)
}

func segue(sender: UIButton) {
    // Perform segue and other stuff
    sender.title // This is the area code
}

关于swift - 从 TableViewCell 中的按钮执行 Segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38535349/

相关文章:

swift - 如何在 iOS UI 测试中查询 "Main Window"?

ios - ios swift中的搜索栏

java - 表格 View 刷新问题

ios - 表格 View 单元格偏移

ios - 如何检测是否正在为 Swift 中的设备或模拟器构建应用程序

ios - 使用 Swift 裁剪图像并将其放在中心位置

Swift Segue 从 UIBarButtonItem

iOS segue 两次屏幕

ios - 如果已经授权,如何跳过登录场景直接从下一步开始?

ios - 如何在 Swift 中解析这个日期时间