When I add a button programmatically to the custom UICollectionViewCell class, it is not clickable and will not run the function I attached to it.
I have tried these so far:
but did not get any luck.
In my cell Class, I have:
let toggleButton: UIButton = {
let tb = UIButton(type: .custom) as UIButton
tb.setTitleColor(.white, for: .normal)
tb.setTitle("Example", for: .normal)
tb.titleLabel?.font = UIFont.customFont(name: "InterUI-Medium", size: 18)
tb.backgroundColor = UIColor(red:0.36, green:0.69, blue:0.55, alpha:1.0)
tb.layer.cornerRadius = 5
tb.titleLabel?.adjustsFontSizeToFitWidth = true
tb.titleLabel?.minimumScaleFactor = 0.4
tb.translatesAutoresizingMaskIntoConstraints = false
tb.addTarget(self, action: #selector(topButtonTouched), for: .touchUpInside)
return tb
}()
and
func setupView() {
self.addSubview(toggleButton)
let menuAndToggleConstraints = [
toggleButton.centerYAnchor.constraint(equalTo: self.centerYAnchor),
toggleButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -100,
toggleButton.widthAnchor.constraint(equalToConstant: 150)
]
NSLayoutConstraint.activate(menuAndToggleConstraints)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
to setup the button in the cell. I have tried self.isUserInteractionEnabled to see if there are any conflicts but it does not resolve anything. I have one other gesture recognizer in the cell and have tried without it and the button is still not clickable.
Edit: Here is my delegate and my function that calls the collectionView to change the size at indexPath:
weak var delegate: ExpandedCellDelegate?
public var indexPath: IndexPath!
@objc func topButtonTouched(_ sender: UIButton) {
print("hello")
if let delegate = self.delegate{
delegate.topButtonTouched(indexPath: indexPath)
}
}
I made sure to set the delegate and indexPath as self in cellForRow function in CollectionView class as demonstrated in this answer.