Detecting which UIButton was pressed in a UITableView

前端 未结 26 3347
小蘑菇
小蘑菇 2020-11-22 00:40

I have a UITableView with 5 UITableViewCells. Each cell contains a UIButton which is set up as follows:

- (UITableView         


        
26条回答
  •  清歌不尽
    2020-11-22 00:54

    I use a solution that subclass UIButton and I thought I should just share it here, codes in Swift:

    class ButtonWithIndexPath : UIButton {
        var indexPath:IndexPath?
    }
    

    Then remember to update it's indexPath in cellForRow(at:)

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let returnCell = tableView.dequeueReusableCell(withIdentifier: "cellWithButton", for: indexPath) as! cellWithButton
        ...
        returnCell.button.indexPath = IndexPath
        returnCell.button.addTarget(self, action:#selector(cellButtonPressed(_:)), for: .touchUpInside)
    
        return returnCell
    }
    

    So when responding to the button's event you can use it like

    func cellButtonPressed(_ sender:UIButton) {
        if sender is ButtonWithIndexPath {
            let button = sender as! ButtonWithIndexPath
            print(button.indexPath)
        }
    }
    

提交回复
热议问题