【问题标题】:UIButton selector is not workingUIButton 选择器不起作用
【发布时间】:2018-06-22 17:11:40
【问题描述】:

我有一个视图,它被放置为 navigationController 的子视图,以填充整个显示。在这个视图中,我有一个包含两个按钮的子视图。 “删除并完成”。然后它还有一个日期选择器。 datePicker 有效,但是 Remove 和 Done 按钮不会触发操作功能。

按钮:

 var setButton: UIButton = {
   var button = UIButton(type: .system)
    button.setTitle("Done", for: .normal)

    button.tintColor = .white
    button.addTarget(self, action: #selector(handleReminderSetBtn), for: .touchUpInside)

    return button
}()

var cancelButton: UIButton = {
    var button = UIButton(type: .system)
    button.setTitle("Remove", for: .normal)
    button.tintColor = .white
    button.addTarget(self, action: #selector(handleReminderCancelBtn), for: .touchUpInside)

    return button
}()

navigationController 中的主要 blackView:

   viewOverLay.addSubview(cardreminder1)

   viewOverLay.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)

   viewOverLay.backgroundColor = UIColor.black.withAlphaComponent(0.3)
   self.navigationController?.view.addSubview(viewOverLay)

CardReminder1 是我有两个按钮的 UIView。

我认为两个按钮的 addTarget 方法中的目标存在一些问题。可能是什么问题?

【问题讨论】:

    标签: ios swift button uiview uinavigationcontroller


    【解决方案1】:

    您不应该以这种方式初始化 setButtoncancelButton

    引用来自Setting a Default Property Value with a Closure or Function 的 Apple 文档:

    如果您使用闭包来初始化属性,请记住实例的其余部分在执行闭包时尚未初始化。这意味着您不能从闭包中访问任何其他属性值,即使这些属性具有默认值。 此外:

    您也不能使用隐式 self 属性,或调用任何实例的方法,因此 问题 在这里:

    addTarget(self...)
    

    所以要解决这个问题,您应该在 CardReminder1 完全初始化后移动按钮初始化(或移动 addTarget)。

    【讨论】:

    • 宾果游戏!非常感谢! :)
    【解决方案2】:

    我刚刚遇到了类似的问题。随着发布的其他答案,使属性lazy 也适用于我的情况。这取决于您第一次尝试访问该属性的时间,但在我的情况下,我只是在初始化完成后才访问它,因此使属性 lazy 工作得很好。

    例如,在您的情况下,以下可能有效:

    lazy var setButton: UIButton = {
        var button = UIButton(type: .system)
        button.setTitle("Done", for: .normal)
    
        button.tintColor = .white
        button.addTarget(self, action: #selector(handleReminderSetBtn), for: .touchUpInside)
    
        return button
    }()
    
    lazy var cancelButton: UIButton = {
        var button = UIButton(type: .system)
        button.setTitle("Remove", for: .normal)
        button.tintColor = .white
        button.addTarget(self, action: #selector(handleReminderCancelBtn), for: .touchUpInside)
    
        return button
    }()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 2013-05-03
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多