以编程方式添加到collectionviewcell时未启用按钮

时间:2018-12-05 06:15:06

标签: swift uibutton uicollectionviewcell

当我以编程方式将按钮添加到自定义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)
    }
}

我确保在this answer中演示了如何在CollectionView类的cellForRow函数中将委托和indexPath设置为self。

1 个答案:

答案 0 :(得分:0)

我可以通过以下操作使按钮起作用:

tb.addTarget(self, action: #selector(topButtonTouched), for: .touchUpInside)

像这样进入setupView()方法:

func setupView() {
    self.addSubview(toggleButton)
    toggleButton.addTarget(self, action: #selector(topButtonTouched), for: .touchUpInside)

    let menuAndToggleConstraints = [
        toggleButton.centerYAnchor.constraint(equalTo: self.centerYAnchor),
        toggleButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -100,
                                               toggleButton.widthAnchor.constraint(equalToConstant: 150)
            ]
            NSLayoutConstraint.activate(menuAndToggleConstraints)
}

不确定是否正确,但是可以。