我有一个带有按钮的 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/