我在另一个TableView内有一个TableView,并且内部tableView包含按钮。我可以在单击按钮时触发一种方法,但无法获取indexPath。当我使用以下代码时,应用程序崩溃

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell") as! MyCell
    cell.myButton?.addTarget(self, action:#selector(myButtonPressed(_:)), for:.touchUpInside)
    return cell
}

@objc func myButtonButtonPressed(_ sender: AnyObject) {
    let button = sender as? UIButton
    let cell = button?.superview?.superview as? UITableViewCell
    let clasObj = myCell()
    let indexPath = myCell.InsidetabView.indexPath(for: cell!)
    let index = (indexPath?.row)!
    print(index)
}

最佳答案

我给TableView, cellForRowAt indexPath方法上的按钮添加了标记,并通过buttonPressed方法访问了它

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell") as! MyCell
    cell.myButton?.addTarget(self, action:#selector(myButtonPressed(_:)), for:.touchUpInside)

    cell.button.tag = indexPath.row

    return cell
}

@objc func myButtonButtonPressed(_ sender: AnyObject) {
    let button = sender as? UIButton
    let row = button!.tag
}

10-07 19:56
查看更多