ios - swift 4 : UIButton not working

标签 ios swift uibutton

在我的应用程序中,我试图支持一个 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/

相关文章:

ios - 在 UITableView 中禁用删除但启用移动单元格

ios - API JSON 和 UIPageViewController 可选 Nil

ios - UICollectionView - 复制 Photos.app 功能

ios - 更新选项卡栏 View Controller 中的文本标签

ios - UIButton 图片饱和度变化

ios - AudioKit 4.2 中 AKSampler.loadMelodicSoundFont 的替代品是什么?

ios - 在 View Controller 中包装 Collection View nil delegate 错误

swift - 如何在 Xcode 7.2 XCTestCase 中获取 ScrollView 的标签?

ios - 无法使 UIButton 的图层蒙版起作用

ios - 将 UIButton 添加到 UITableView 的 detailTextLabel/右侧