簡體   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