在我的应用程序中,我试图支持一个 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")
}
然后我将按钮添加到 View 中:
view.addSubview(tbutton)
我是否遗漏了一段代码,或者我编码有误?
最佳答案
你不应该以那种方式初始化你的按钮。
引用来自 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:
您也不能使用隐式 self 属性,或调用实例的任何方法,因此问题就在这里:
button.addTarget(self, action: #selector(dothings), for: .touchUpInside)
因此,要解决此问题,您应该在 ViewController 完全初始化后移动按钮初始化(或移动 addTarget)(例如:viewDidLoad
)。
解决此问题的另一种方法,假设您仅在 viewDidLoad
之后使用此类按钮,将其定义为 lazy var
:
A lazy stored property is a property whose initial value is not calculated until the first time it is used
关于ios - swift 4 : UIButton not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48248971/