【问题标题】:Passing index path information to button action from cell Swift将索引路径信息从单元格 Swift 传递给按钮操作
【发布时间】:2015-08-13 15:21:40
【问题描述】:

我有这个:

let mapsbut = cell.viewWithTag(912) as! UIButton
mapsbut.addTarget(self, action: "mapsHit:", forControlEvents: UIControlEvents.TouchUpInside)

和

func mapsHit(){

    // get indexPath.row from cell
    // do something with it

}

这是如何实现的?

【问题讨论】:

  • 你的第一个代码sn-p在什么方法里面?
  • @iosDev82 这个问题在 Objective C 中
  • 上面发布的链接有一些答案,但另一种方法是在创建自定义单元格时将 indexPath 分配给自定义 UITableViewCell 子类的属性。 action 方法可以在子类中,您可以使用 postNotification 或通过协议的委托来指示控制器应该采取一些行动。您可以在 SO 中搜索此问题的许多具体解决方案。

标签: ios swift uitableview button action


【解决方案1】:

您始终可以使用按钮中的 tag 来传递或保存一个值,或者在您的自定义单元格实现中保留一个 var。例如,如果您在UITableViewCell 中将按钮作为outlet(例如):

class MenuViewCell: UITableViewCell {

    @IBOutlet weak var titlelabel: UILabel!
    @IBOutlet weak var button: UIButton! {
        didSet {
            button.addTarget(self, action: "mapsHit:", forControlEvents: UIControlEvents.TouchUpInside)
          }
    }
    func mapsHit(sender: UIButton){
        let indexPathOfThisCell = sender.tag
        println("This button is at \(indexPathOfThisCell) row")
        // get indexPath.row from cell
        // do something with it

    }
}

在此注意,设置"mapsHit:"时需要将sender:UIButton设置为参数。这将是用户点击的按钮本身。

现在,要使其正常工作,您的标签不能是 “912”。相反,当您构建单元格时,分配给按钮的 tag 属性,它的值是 indexPath。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("MenuViewCell", forIndexPath: indexPath) as! MenuViewCell

        cell.titlelabel?.text = data[indexPath.row].description
        cell.button.tag = indexPath.row
        return cell
    }

【讨论】:

  • 这不起作用。您不能将 IndexPath 转换为 Int。
  • ...因为这是我做 indexPath.row
【解决方案2】:

...一个解决方案可能是在你的类中使用一个 var 来保存最后一个被点击的单元格的 indexPath,然后你可以在你的 mapsHit() 函数中使用该值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 2017-11-21
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多