【问题标题】:I'm trying to populate a custom cell with an action button我正在尝试使用操作按钮填充自定义单元格
【发布时间】:2016-12-13 05:32:51
【问题描述】:

我正在使用自定义单元格类来快速填充表格视图。

我需要让它为一组按钮工作,以便每个单元格都有一个按钮,该按钮执行该单元格独有的 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
  }

【问题讨论】:

  • 为此无需复杂,只需在 cellforrow 方法中分配标签,如下所示: sender.tag == yourvalue 使其工作
  • 我仍在努力暗示这一点。我仍然无法将 performTask 链接到函数任务
  • ping 我,现在你被卡住了,我会帮你解决的
  • 不好意思说我不知道​​这意味着什么……假设它正在远程进入我的项目?

标签: swift uitableview tableview ibaction


【解决方案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)
    }
}

在视图控制器中:

 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    相关资源
    最近更新 更多