Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UIButton选择器不工作_Ios_Swift_Button_Uiview_Uinavigationcontroller - Fatal编程技术网

Ios UIButton选择器不工作

Ios UIButton选择器不工作,ios,swift,button,uiview,uinavigationcontroller,Ios,Swift,Button,Uiview,Uinavigationcontroller,我有一个视图作为navigationController的子视图放置,以填充整个显示。在这个视图中,我有一个子视图,它有两个按钮。“删除并完成”。还有一个日期选择器。datePicker可以工作,但是,Remove和Done按钮没有启动操作功能 按钮: var setButton: UIButton = { var button = UIButton(type: .system) button.setTitle("Done", for: .normal) button.

我有一个视图作为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方法中的target存在一些问题。有什么问题吗?

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

引用苹果公司的文档:

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

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

addTarget(self...)

因此,要解决此问题,您应该在
卡提醒1
完全初始化后移动初始化按钮(或移动
添加目标)。

我刚刚遇到类似问题。与发布的另一个答案一样,使属性
懒惰
在我的案例中也起了作用。这取决于您第一次尝试访问该属性的时间,但在我的例子中,我只是在初始化完成后才访问它,因此使属性
惰性
非常有效

例如,在您的案例中,以下操作可能有效:

lazy var setButton:ui按钮={
var按钮=UIButton(类型:。系统)
button.setTitle(“完成”,用于:。正常)
button.tintColor=.white
button.addTarget(self,action:#选择器(handleReminderSetBtn),for:.touchUpInside)
返回按钮
}()
惰性var取消按钮:UIButton={
var按钮=UIButton(类型:。系统)
button.setTitle(“删除”,用于:。正常)
button.tintColor=.white
button.addTarget(self,action:#选择器(handleReminderCancelBtn),用于:。touchUpInside)
返回按钮
}()

BINGO!非常感谢!:)