首页 > 解决方案 > 自定义单元格中的按钮索引

问题描述

我创建了一个包含按钮的自定义单元格,我需要创建从这个按钮到其他 VC 的 segue,但首先,我想用那个 segue 推送一个对象。

我已经尝试使用 cell.button.tag,但我没有成功。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "showMap" {
            let mapVC = segue.destination as! MapViewController
            //guard let indexPath = tableView.indexPathForSelectedRow else { return }
            mapVC.place = places[] // <- "here I need index of button in cell"
        }
    }

标签: iosswiftuitableview

解决方案


而不是使用,而是通过in以编程方式segue处理。navigationclosureUITableViewCell

class CustomCell: UITableViewCell {
    var buttonTapHandler: (()->())?

    @IBAction func onTapButton(_ sender: UIButton) {
        self.buttonTapHandler?()
    }
}

在上面的代码中,我创建了buttonTapHandler一个-a ,只要点击内部closure,就会调用它。buttoncell

现在,在cellForRowAt您的单元格中,dequeue设置buttonTapHandler.CustomCell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
    cell.buttonTapHandler = {[weak self] in
        if let mapVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MapViewController") as? MapViewController {
            mapVC.place = places[indexPath.row]
            self?.navigationController?.pushViewController(mapVC, animated: true)
        }
    }
    return cell
}

在上面的代码中,buttonTapHandler当被调用时,将push创建一个新的实例MapViewController以及相关place的基于indexPath.


推荐阅读