简体   繁体   English

Swift4:UIButton不起作用

[英]Swift4: UIButton not working

Within my app i'm trying to back a UIButton, i just want it to print "this is a test" When i press the button it does the classic button animation, however there is nothing printed in the console. 在我的应用程序中,我试图支持UIButton,我只希望它打印“这是一个测试”。当我按下按钮时,它会执行经典的按钮动画,但是控制台中没有任何打印内容。

var tbutton: UIButton = {
    let button = UIButton(type: .system)
    button.frame = CGRect(x: 40.0, y:400.0, width: 300.0, height: 300.0)
    let image = UIImage(named: "backb")
    button.setBackgroundImage(image, for: .normal)
    button.addTarget(self, action: #selector(dothings), for: .touchUpInside)
    return button
}()

@objc func dothings(){
    print("this is a test")

}

I then add the button into view with: 然后,我将按钮添加到视图中:

view.addSubview(tbutton)

Is there a section of code i'm missing, or have i coded something wrong? 我是否缺少一部分代码,或者我编码有误?

You shouldn't initialize your button in that way. 您不应该以这种方式初始化按钮。

Quoting the Apple documentation from Setting a Default Property Value with a Closure or Function : 引用Apple文档中的“ 使用闭包或函数设置默认属性值”

If you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. 如果使用闭包来初始化属性,请记住在执行闭包时实例的其余部分尚未初始化。 This means that you cannot access any other property values from within your closure, even if those properties have default values. 这意味着您无法从闭包内部访问任何其他属性值,即使这些属性具有默认值也是如此。 moreover: 此外:

You also cannot use the implicit self property, or call any of the instance's methods, hence the problem is here: 您也不能使用隐式的self属性,或调用实例的任何方法,因此问题出在这里:

button.addTarget(self, action: #selector(dothings), for: .touchUpInside)

so to fix the issue you should move the button initialization (or move the addTarget) after your ViewController is fully initialized (eg: viewDidLoad ). 因此,要解决此问题,您应该在ViewController完全初始化后移动按钮初始化(或移动addTarget)(例如: viewDidLoad )。


Another way to fix the issue, assuming you are using such button only after viewDidLoad , is to define it as a lazy var : 解决此问题的另一种方法(假设仅在viewDidLoad之后使用此类按钮)是将其定义为lazy var

A lazy stored property is a property whose initial value is not calculated until the first time it is used 惰性存储属性是其首次使用后才计算其初始值的属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM