2016-07-22 59 views
1

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

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 
    } 
} 
+0

因此,您有多个“CustomCell”单元,每个单元都有一个按钮可以完成不同的操作? – gadu

+0

使用'cell.button.tag = indexPath.row' – Lamar

+0

如果您希望同一个表的单元格延伸到不同的视图,则必须为它们提供不同的重用标识符。 – orccrusher99

回答

1

有一堆的方式获得您的自定义单元格的龙头作用,但我假设你想,因为你想Segue公司检索从UIViewController的动作。

因为您正在将一个单元出队,所以您可以简单地在您的cellForRowAtIndexPath函数的范围内完全访问单元。只要您将按钮作为单元格的公共属性,您可以将该按钮的目标设置为您的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 
} 
+0

谢谢,我正在尝试这个;但是,传递的值始终是我的tableView中的最后一个值 –

+0

我可以请求查看您的代码吗? – jimmyy

+0

我将它添加到主帖 –