如何在表格视图单元格

时间:2015-11-06 07:23:54

标签: ios parameter-passing swift2 viewcontroller

我在按钮中添加了目标

cell.foo.tag = indexPath.row
cell.foo.addTarget(self, action: "bar:", forControlEvents:UIControlEvents.TouchUpInside)

但我不知道如何使用参数调用视图控制器

func bar(sender: UIButton!) {
   // ?
}

1 个答案:

答案 0 :(得分:1)

您必须使用发件人代码手动

func bar(sender: UIButton!) {

    if sender.tag == 0 {

        self.performSegueWithIdentifier("viewcontroller1", sender: tableView)
    }
    else if sender.tag == 1 {

        self.performSegueWithIdentifier("viewController2", sender: tableView)
    }
    //...... and so on
}

并实施以下方法

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

    if segue.identifier == "viewController1" {

        let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow()!
        let detailVC = segue.destinationViewController as ViewController1
        detailVC.item = items[indexPath.row] as Item // Pass your data
    }
    else if segue.identifier == "viewController2" {


    }
    //...... and so on
}

或者,如果您想从按钮事件手动导航,那么

func bar(sender: UIButton!) {

    if sender.tag == 0 {

        let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow()!
        let detailVC = self.storyboard?.instantiateViewControllerWithIdentifier("view1SegueIdentifier") as! ViewController1 // view1SegueIdentifier -> assign it from storyboard
        detailVC.item = items[indexPath.row] as Item // Pass your data
        self.navigationController!.pushViewController(detailVC, animated:true)
    }
    else if sender.tag == 1 {


    }
    //...... and so on
}