【问题标题】:Clicking A Button In A CollectionViewCell单击 CollectionViewCell 中的按钮
【发布时间】:2017-07-15 03:09:50
【问题描述】:

我正在向集合视图单元格的自定义类添加一个按钮,但无法点击它。

这是我在单元格自定义类中声明按钮的方式:

let shareBtn: UIButton = {
    let roundBtn = UIButton()
    roundBtn.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
    roundBtn.layer.cornerRadius = 35
    roundBtn.layer.shadowOpacity = 0.25
    roundBtn.layer.shadowRadius = 2
    roundBtn.setImage(UIImage(named: "share"), for: .normal)
    roundBtn.addTarget(self, action: #selector(shareAction(button:)), for: .touchUpInside)
    roundBtn.isUserInteractionEnabled = true
    roundBtn.isEnabled = true

    return roundBtn
}()

选择器调用的方法如下:

func shareAction(button: UIButton){
    print("shareAction")
}

我如何在初始化中添加按钮

override init(frame: CGRect) {
    super.init(frame: frame)

    contentView.addSubview(shareBtn)

    shareBtn.translatesAutoresizingMaskIntoConstraints = false
    shareBtn.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -100).isActive = true
    shareBtn.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
    shareBtn.widthAnchor.constraint(equalToConstant: 70).isActive = true
    shareBtn.heightAnchor.constraint(equalToConstant: 70).isActive = true

我尝试将按钮添加到两者 - contentView 和 self 但都给出相同的结果,这是不可点击的按钮。

欢迎提出任何建议。

【问题讨论】:

    标签: ios swift uibutton uicollectionviewcell


    【解决方案1】:

    使用每次访问shareBtn 时创建按钮的方式,您总是在创建一个新实例,因为它是一个计算变量。这就是为什么当你写这个的时候:

    addSubview(shareBtn)
     shareBtn.addTarget(self, action: #selector(shareAction(button:)), for: .touchUpInside)
    

    添加为子视图的按钮和添加目标的按钮是不同的实例。您必须为 shareBtn 使用 lazy var,如下所示:

    lazy var shareBtn: UIButton = {
        let roundBtn = UIButton()
        roundBtn.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
        roundBtn.layer.cornerRadius = 35
        roundBtn.layer.shadowOpacity = 0.25
        roundBtn.layer.shadowRadius = 2
        roundBtn.setImage(UIImage(named: "share"), for: .normal)
        roundBtn.addTarget(self, action: #selector(shareAction(button:)), for: .touchUpInside)
        roundBtn.isUserInteractionEnabled = true
        roundBtn.isEnabled = true
    
        return roundBtn
    }()
    

    这样,当您第一次访问它时,只会创建一个实例并将其分配给shareBtn,并且所有后续访问都将使用同一个实例。

    【讨论】:

    • 什么?伙计,你是对的。为什么 swift 会这样做,为什么要创建它的新实例是相同的常数,我不明白。谢谢
    【解决方案2】:

    按钮位于父视图控制器中添加的页面控制视图下。我还需要在将子视图添加到单元格后调用操作方法:

     addSubview(shareBtn)
     shareBtn.addTarget(self, action: #selector(shareAction(button:)), for: .touchUpInside)
    

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 2018-04-04
      • 2015-10-18
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 2019-01-11
      相关资源
      最近更新 更多