Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 在TableViewCell中执行从按钮的切换_Swift_Tableview_Segue - Fatal编程技术网

Swift 在TableViewCell中执行从按钮的切换

Swift 在TableViewCell中执行从按钮的切换,swift,tableview,segue,Swift,Tableview,Segue,我有一个CustomCell类,它有一个按钮。我使用的是一个原型单元(不是.xib)。我想让tableviewcell中的按钮执行一个segue并将一个值传递给一个新类。如何为tableviewcell中的按钮创建唯一操作?谢谢 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { ... selected

我有一个CustomCell类,它有一个按钮。我使用的是一个原型单元(不是.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
检索操作,因为您正在尝试分段

由于您正在将单元格出列,因此您可以在
cellforrowatinexpath
函数的作用域内短暂地完全访问该单元格。只要按钮是单元格的公共属性,就可以将该按钮的目标设置为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
}

因此,您有多个“CustomCell”单元格,每个单元格都有一个执行不同操作的按钮?请使用该按钮
cell.button.tag=indexPath.row
如果希望同一表中的单元格切换到不同的视图,则必须为它们提供不同的重用标识符。它们都执行相同的切换,但我希望每个按钮传递的值都不同。例如:数组[“1”、“2”、…],其中单元格1-将“1”传递给HomeView,单元格2-将“2”传递给HomeView,等等。但是现在,我已经为按钮添加了一个目标来继续,但它只传递了数组中的最后一个数量,我正在尝试这个;但是,传递的值始终是我的TableView中的最后一个值。我将把它添加到主postateded,try it out我将尝试!实际上,我通过使用
cell.areaCodeButton.addTarget=indexPath.row
向按钮添加一个标记来实现它,然后在segue函数中,我将selectedaracode设置为
selectedaracode=areaCodes[sender.tag]
,它就可以工作了!谢谢