【发布时间】:2018-12-05 06:15:06
【问题描述】:
当我以编程方式将按钮添加到自定义 UICollectionViewCell 类时,它不可点击并且不会运行我附加到它的功能。
到目前为止我已经尝试过这些:
但没有得到任何运气。
在我的单元格类中,我有:
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
}()
和
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()
}
在单元格中设置按钮。我试过 self.isUserInteractionEnabled 来查看是否有任何冲突,但它没有解决任何问题。我在单元格中还有另一个手势识别器,我试过没有它,但按钮仍然不可点击。
编辑: 这是我的委托和调用 collectionView 以更改 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)
}
}
我确保在 CollectionView 类的 cellForRow 函数中将委托和 indexPath 设置为 self,如 this answer 中所示。
【问题讨论】:
标签: swift uibutton uicollectionviewcell