2016-12-13 71 views
0

我正在使用自定义单元格类来在swift中填充tableview。我想用行动按钮填充自定义单元格

我需要得到它的按钮数组,使每个单元格有一个按钮,执行该单元格的独特IBAction功能。

这里是我的电池类声明按钮变量:

class taskCell: UITableViewCell { 
    @IBOutlet weak var performTask: UIButton! 
    //ignoring code irrelevant to question 
} 

所有的,我想,当按下按钮发生我的“任务”是以下模式的变化:

@IBAction func task1(sender: AnyObject){ 
    if (prerequisite1 >= 1) { 
     prerequisite1 = prerequisite1 - 1; 
     points = points + 400; 
     prerequisite1Label.text = "\(prerequisite1)"; 
     pointsLabel.text = "\(points)"; 
    } 
} 

@IBAction func task2(sender: AnyObject){ 
     if (prerequisite2 >= 1) { 
      prerequisite2 = prerequisite2 - 1; 
      points = points + 600; 
      prerequisite1Label.text = "\(prerequisite2)"; 
      pointsLabel.text = "\(points)"; 
     } 
    } 

这里是我试图把它们放在我的viewController中的一个数组中,该表位于:

let firstTasks:[()->()] = [tasksViewController().task1(), tasksViewController().task2()] 

最后这里是我实现它在tableview中实现它的企图:

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

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! JobCell 
     cell.performTask.tag = indexPath.row 
     cell.performTask.addTarget(self, action: firstTasks[indexpath.row], forControlEvents: .TouchUpInside)  

     return cell 
    } 
+1

,强制在这样cellforrow方法分配标签:cell.performtask.tag = indexpath.row,然后当你的方法调用时,你可以将它的arguemnt(sender)作为sender.tag == yourvalue来使它工作 –

+0

我仍然在嘲讽这个。我仍然无法将performTask链接到功能任务 –

+0

ping me,现在你卡住了,我会帮你解决 –

回答

1

而不是保持功能阵列。你为什么不这样做:

class JobCell: UITableViewCell { 
    @IBOutlet weak var performTask: UIButton! 
    var actionBlock: (sender: AnyObject?) -> Void?   

    func someFunc() { 
     performTask. addTargetself, action: #selector(JobCell.didTapButton(_:)), forControlEvents: .TouchUpInside) 
    } 

    func didTapButton(sender: AnyObject) { 
     actionBlock?(sender) 
    } 
} 

在的viewController:这个没有必要使其复杂

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

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! JobCell 
    cell.actionBlock = {(sender) in 
     // do ur thing 
    } 
    return cell 
}