0

我在添加 barButtons 时遇到了一些问题,并在另一个问题的答案中找到了解决方案,但它没有解释为什么必须在同一范围内创建和添加按钮。我想知道为什么不能在类级别创建按钮并将它们添加到 viewDidLoad 之类的方法中。从下面复制的该问题中不起作用的示例代码:

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
}

这会得到一个无法识别@objc 方法的错误(此处不包括)。这些方法没有任何问题,因为当您在 viewDidLoad 中移动按钮创建时,错误消失并且代码有效。

4

2 回答 2

4

这些条形按钮属性是在调用 init 之前创建的,并且您正在尝试访问在调用 init 之前无法调用的类方法。

如果要在类范围内初始化按钮,则必须使它们成为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))
于 2019-04-26T04:26:43.393 回答
-1
     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
    }
于 2019-04-26T04:43:49.657 回答