gpt4 book ai didi

ios - UIButton 的 lazy var 或 let

转载 作者:行者123 更新时间:2023-11-29 01:16:35 25 4
gpt4 key购买 nike

当我想在 View Controller 的 View 中添加 UIButton 时,方法如下:

首先

let button: UIButton = UIButton()

然后在viewDidLoad方法中配置属性。

第二

lazy var button: UIButton = {
let buttonTemp = UIButton()
buttonTemp.backgroundColor = UIColor.clearColor()
button.addTarget(self, action: "connect", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(buttonTemp)
return buttonTemp
}()

第三

let button: UIButton = {
let button = UIButton(type: .Custom)
button.backgroundColor = UIColor.greenColor()
return button
}()

我的问题是我应该使用哪种方式或者哪种方式更好?

  1. 我不喜欢第一种方法,因为我必须添加额外的方法来配置其他属性。

  2. 第二个对我来说没问题,我只需要在任何我想要的地方调用 button 即可。

  3. 我认为使用 let 是最好的,所以我使用第三种方式,但问题是我无法调用 self,如果我在闭包中添加此链接:

    button.addTarget(self, action: "connect", forControlEvents: UIControlEvents.TouchUpInside)

我得到了错误:

ViewController.swift:24:26:无法将“NSObject -> () -> ViewController”类型的值转换为预期参数类型“AnyObject?”

所以我在这个闭包中添加了这一行(任何带有 self 的行)。有什么办法可以解决这个问题吗?

总结一下,哪种方式更好或者更适合?或者有什么更好的方法吗?谢谢!

编辑:

当我使用 Objective C 时,我想以这种方式使用 getter

- (UIButton *) button {
if (!_button) {
_button = [[UIButton alloc] init];
_button.backgroundColor = [UIColor redColor];
...
}
return _button;
}

这样我的viewDidLoad就会干净并且看起来不错:

- (void) viewDidLoad {
...
[self.view addSubview:self.button];
...
}

最佳答案

风格显然各不相同,但在我工作的地方,我们已经标准化了以下方法:

class ViewController: UIViewController {
private var button: UIButton!

override func viewDidLoad() {
super.viewDidLoad()

button = {
let button = UIButton(type: .Custom)

button.addTarget(self, action: "buttonTouched:", forControlEvents: .TouchUpInside)
button.otherProperty = ...

return button
}()

view.addSubview(button)

// add constraints for button
}

func buttonTouched(sender: UIButton) {
print("boop")
}
}

您所有方法的问题在于:

  • 它们非常冗长并且不包含在函数中,并且
  • 如您所见,您无权访问 self

通过上述方法(使用强制解包可选),您可以获得延迟初始化的好处(即一切都发生在 viewDidLoad() 中),您知道,因为您拥有该对象 button 永远不会是 nil (因此您不必到处使用条件绑定(bind)),并且您可以为所有 UIView 进行包含的初始化> 属性集中在一处。

显然,您可以(我们也这样做)使您的 viewDidLoad() 函数如下所示:

override func viewDidLoad() {
super.viewDidLoad()

createViews()
addSubviews()
addViewConstraints()
}

然后,您可以更好地特化您的功能,并且您的代码保持井井有条。

关于ios - UIButton 的 lazy var 或 let,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35110273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com