Ios lazy-var或let-for-ui按钮
当我想在视图控制器的视图中添加Ios lazy-var或let-for-ui按钮,ios,swift,Ios,Swift,当我想在视图控制器的视图中添加ui按钮时,有以下几种方法: 首先 let button: UIButton = UIButton() 然后在viewDidLoad方法中配置属性 秒 lazy var button: UIButton = { let buttonTemp = UIButton() buttonTemp.backgroundColor = UIColor.clearColor() button.addTarget(self, action: "connec
ui按钮时,有以下几种方法:
首先
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
}()
第三
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
}()
我的问题是我应该用哪种方法,或者哪种方法更好
我不喜欢第一种方法,因为我必须添加一个额外的方法来配置其他属性
第二个对我来说没问题,我只需要在任何我想去的地方按一下按钮
我认为use-let最合适,所以我使用第三种方式,但问题是我不能调用self
,如果我在闭包中添加此链接:
button.addTarget(自身,操作:“连接”,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()
中发生的一切),因为您拥有对象,所以按钮将永远不会为零(因此您不必到处使用条件绑定),您可以在一个位置获得所有UIView
属性的包含初始化
显然,您可以(我们也可以)使您的viewDidLoad()
函数如下所示:
override func viewDidLoad() {
super.viewDidLoad()
createViews()
addSubviews()
addViewConstraints()
}
然后,你的函数会得到更好的专门化,你的代码也会保持有序。在一个庞大的团队中,故事板和NIB通常都是一个巨大的难题。如果有很多控件,viewDidLoad
将非常长。这就是为什么我在使用专门化函数的最后给出了一个示例。将视图初始化放入createViews()
等。