繁体   English   中英

在 viewdidload 之外更新导航栏按钮项目标题

[英]Updating navigation bar button item title outside of viewdidload

我正在使用以下代码在viewDidLoad方法中创建一个导航栏:

   let backButtonImage = UIImage(named: "backButton")
    normalButton = UIButton(frame: CGRect(x: 0, y: 0, width: backButtonImage!.size.width, height: backButtonImage!.size.height))
    normalButton.setImage(backButtonImage, for: .normal)

    normalButton.setTitleColor(.systemBlue, for: .normal)
    normalButton.contentHorizontalAlignment = .leading
    normalButton.contentVerticalAlignment = .center
    normalButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0.0, bottom: 0.0, right: 0.0)

    let backBarButton = UIBarButtonItem(customView: normalButton)
    backBarButton.tintColor = .systemBlue


    item.leftBarButtonItems = [backBarButton]

    navigationBar.isTranslucent = false
    navigationBar.barTintColor = .white

    self.view.addSubview(navigationBar)
    navigationBar.translatesAutoresizingMaskIntoConstraints = false

    navigationBar.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    navigationBar.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    navigationBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true



    navigationBar.items = [item]
    navigationBar.delegate = self

但是我想在用户触摸视图内的另一个按钮时更新 normalButton 标题。 我尝试了以下代码:

    if let letnavItem = navigationBar.items?[0],let bb = letnavItem.leftBarButtonItems?[0] {
        if let but = bb.customView, let but2 = but as? UIButton {
            print("counter: \(counter)")
            but2.setTitle("asd", for: .normal)
        }
    }

但它不起作用。 但是如果我在 navigationBar.delegate 行之后在viewDidLoad方法中运行第二个代码,它运行良好。

为什么它不能在viewDidLoad之外工作?

以上所有代码都是正确的,只是您需要在设置按钮文本之前从按钮中删除图像,如下所示:

but2.setImage(nil, for: .normal)
but2.setTitle("asd", for: .normal)

暂无
暂无

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

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