简体   繁体   English

如果在添加范围之外创建barBarttonItem,为什么无法添加它呢?

[英]Why adding barBarttonItem won’t work if created out of scope where it’s added?

I ran into some problems when adding barButtons and found the solution in the answer to another question , but the it didn't explain why you must create and add the buttons in the same scope. 添加barButtons时遇到了一些问题,并在另一个问题的答案中找到了解决方案,但是它没有解释为什么必须在同一范围内创建和添加按钮。 I want to know why you can't create the buttons in class level and add them in a method like viewDidLoad. 我想知道为什么您不能在类级别创建按钮并将其添加到诸如viewDidLoad之类的方法中。 Example code that doesn't work from that question copied below: 对于下面复制的该问题无效的示例代码:

let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(onRightClick))
let leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(onLeftClick))

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.rightBarButtonItem = rightButton
    navigationItem.leftBarButtonItem = leftButton
}

This get an error that won't recognize the @objc methods(not included here). 这将导致无法识别@objc方法的错误(此处未包括)。 There's nothing wrong with those methods, as when you move the button-creations inside viewDidLoad the error disappears and the code works. 这些方法没有什么问题,因为当您在viewDidLoad中移动按钮创建时,错误消失并且代码可以正常工作。

These bar button properties are created before init is called and you're trying to access class methods which can't be called before init is called. 这些bar按钮属性是在调用init之前创建的,并且您尝试访问在调用init之前无法调用的类方法。

If you want to initialize your buttons on class scope, you will have to make them lazy variables in order to create them when they are needed 如果要在类作用域上初始化按钮,则必须使它们成为lazy变量,以便在需要时创建它们

lazy var rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(onRightClick))
lazy var leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(onLeftClick))
     override func viewDidLoad() {
        super.viewDidLoad()

        let leftBarButton = UIBarButtonItem(title: "Left Button", style: .plain, target: self, action: #selector(pressOnleftBarButton))
        navigationItem.leftBarButtonItem = leftBarButton

        let rightBarbutton = UIBarButtonItem(title: "Right Button", style: .plain, target: self, action: #selector(pressOnRightBarButton))
        navigationItem.rightBarButtonItems = rightBarbutton
    }

    @objc func pressOnleftBarButton(){
      //Perform Action on Left Button
    }

    @objc func pressOnRightBarButton(){
        //Perform Action on right Button
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM