Search code examples
iosswiftbuttontableviewindexpath

Access button index from TableView inside another TableView


I have a TableView inside Another TableView, and the inner tableView contains buttons. I am able fire a method when click on button, but not able to get the indexPath. The app is getting crashed when I use the below code

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) 
}

Solution

  • I gave tag to the button on TableView, cellForRowAt indexPath Method and accessed it on buttonPressed method

    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
    }