简体   繁体   中英

UIButton not responding used in a custom UITableViewCell

I know this issue is already been asked few times in SO. Despite trying those out, I am still unable to solve my problem.

I am using a UITableView inside a UIViewController. I have a custom UITableViewCell which has couple of buttons in it. However, I am not able to make the Button respond to Click event.

The development environment is iOS 9 and Swift 2

Snippets used:

BranchNearMeTableViewCell.swift contains

@IBOutlet weak var btnDetails: UIButton!

view controller class

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("branchNearTableCell") as! BranchNearMeTableViewCell

 cell.btnDetails.tag = indexPath.row
        cell.btnDetails.addTarget(self, action: "showDetails:", forControlEvents: .TouchUpInside)

}

func showDetails(sender: UIButton){

        print("Button Pressed:")
    }

Additional Info:

TableView and TableCellView has User interaction disabled in Interface builder since don't want the entire cell to be clickable.

UIButton inside TableViewCell has User Interaction enabled.

Being an iOS noob, I may be making a silly mistake which I might have overlooked.

Similar questions that I checked include:

SO1

SO2

SO3

I Deeply appreciate any help regarding this question.

I faced a similar issue. I was programmatically adding an UIButton to the UITableViewCell via addSubview . The button would not respond to touch events. Using Debug View Hierarchy, I finally discovered that any subviews added to the UITableViewCell was behind contentView , which was blocking user input from reaching the UIButton . The issue was resolved by adding the UIButton to contentView instead of the UITableViewCell .

I would have userInteractionEnabled set to true on the table view cell as well. I would prevent taps using the UITableView allowsSelection to false

Also remember to remove the target and action in tableView:cellForRowAtIndexPath: since the cells are recycled, the button might already have the target and action, it might add a second.

I found a simple solution:

Inherits UITableViewCell, and override init()

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    //init subviews, eg. self.switch = UISwitch()
    super.init(style: style, reuseIdentifier: reuseIdentifier)
                
    // add this line magic code 
    contentView.isUserInteractionEnabled = true
                
    //add subviews, e.g. self.addSubView(self.switch)
}

I came across this issue today, with a button inside a static UITableview cell, that was not responding to user events. I realised the 'Content View' of the cell also has a 'User Interaction Enabled' tick box. Make sure you select the 'Content View' inside the UITableview cell in your Document Outline menu, then tick the box for 'User Interaction Enabled' in the Attributes Inspector - see attached photo for reference. 'User Interaction Enabled' also needs to be checked for the cell for this to work. Hope this helps. XCcode screen shot

您只需要做(在 ViewDidLoad 中):

mTableView.delaysContentTouches = false

For programmatically created views, the only thing to remember is to declare buttons using lazy var in UITableViewCell . And also add subviews to contentView instead of the cell itself For example:

class CounterCell: UITableViewCell {

    lazy var incrementButton: UIButton = {
        let button = UIButton()
        button.setTitle("+", for: .normal)
        button.addTarget(self, action: #selector(incrementAction), for: .touchUpInside)
        return button
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.addSubview(incrementButton)
        // Your constrains here
    }

    @objc func incrementAction() {
    }

}

When using programmatically views, there's no need to add .userInteractionEnabled flags.

Then to take the action out of the cell, just add a delegate and assign it from the UITableViewDataSource .

Also, make sure you are adding target actions to your buttons outside their setup. So instead of

let button: UIButton = {
    //addTarget...
}()

you can have a function to set up your buttons after something happens:

func setButtonsUp() {
    // myButton.addTarget
}

For anyone else struggling, here's my solution:

sendSubviewToBack(cell.contentView)

The thing that there's now an extra UITableViewCellContentView layer which blocks interaction with views behind it. Related issue: An extra UITableViewCellContentView overlay appears in a TableView on iOS 14 preventing taps, but works fine on iOS 13

Ad a first sight nothing seems to be wrong with your code.
So I suggest you to add a background color to the superview of the button, why? because if the button is outside the frame of its superview it will never receive touches.
If you see that the button is not inside the background color probably you have an issue positioning the item, check constraints or whatever you are using. Check also the frame of the button.
You can also do both by inspecting the view at runtime, here a tutorial.

I dont know what wrong in the code but i can suggest which i personally use and it works for me

In BranchNearMeTableViewCell.swift

@IBOutlet var btnDetails: UIButton!
@IBAction func btnDetailsClick(sender: AnyObject) {
    tapButton?(self)
}
var tapButton: (UITableViewCell -> Void)?

In Table view controller

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("branchNearTableCell") as! BranchNearMeTableViewCell

 cell.tapButton = {(user) in
             //User will be tablecell here do whatever you want to do here
        }

}

So if you click on button in table cell this cell.tapButton will be called you can do whatever you want to do here

The only things we need to do is in cellForRowAt just put:

cell.selectionStyle = .none

in this way, UITableview will bypass the touch of selecting cells and allow buttons inside our cells to be clickable.

  • set cell and cell content view isUserInteractionEnabled = true
  • Add Tapgesture to the button
  • Add a closure to handle gesture action

Add target for that button.

button.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

Set tag of that button since you are using it.

button.tag = indexPath.row

Achieve this by subclassing UITableViewCell. button on that cell, connect it via outlet.

Make sure button.isUserInteractionEnabled = true

To get the tag in the connected function:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}

确保所有 tableView 的超级视图都将 isUserInteractionEnabled 设置为 true

You need 2 things. Add this property to UITableView instance:

tableView.delaysContentTouches = false

And add this to your custom UItableViewCell instance inside init:

 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    contentView.isUserInteractionEnabled = true
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM