UIButton使用lazy var还是let?

3
当我想在视图控制器的视图中添加一个 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. 第二种对我来说还可以,我只需要在需要的任何地方调用按钮。
  3. 我认为使用let是最适合的,所以我使用了第三种方式,但问题是我不能调用self,也就是如果我在闭包中添加这个链接:
  4. button.addTarget(self, action: "connect", forControlEvents: UIControlEvents.TouchUpInside)

我得到了这个错误:
ViewController.swift:24:26: Cannot convert value of type 'NSObject -> () -> ViewController' to expected argument type '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];
   ...
}

1
故事板和Nib在一个庞大的团队中通常很难维护。 - par
1个回答

4

显然,风格因人而异,但在我的工作中,我们已经统一采用以下方法:

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(因此您不必在各个地方使用条件绑定),并且您可以在一个地方对所有UIView属性进行初始化。
显然,您可以(我们也这样做)使viewDidLoad()函数看起来像这样:
override func viewDidLoad() {
    super.viewDidLoad()

    createViews()
    addSubviews()
    addViewConstraints()
}

然后您可以更好地专注于函数的特定领域,使您的代码保持组织良好。


如果有很多控件,viewDidLoad会变得非常长。 - William Hu
这就是为什么我在最后举了使用专门函数的例子。将视图初始化放在createViews()中,等等。 - par

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接