0

我在另一个 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) 
}
4

1 回答 1

0

我给 Method 上的按钮添加标签并在方法上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
}
于 2018-12-06T05:20:42.230 回答