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 UIViewCo
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
}
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.
You only have to do (in ViewDidLoad):
mTableView.delaysContentTouches = false
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