当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Set Title to UIBarButtonItem

问题描述:

I have UIBarButtonItem and whenever I try to set title to the button, its not working.

@IBOutlet weak var barButton: UIBarButtonItem!

override func viewDidLoad() {

super.viewDidLoad()

barButton.title = "AB"

}

But if I try to create Action of UIBarButtonItem and then do sender.setTitle() then it works. But not at viewDidLoad. I don't want to set title when user taps on the button.

网友答案:

If you already have an IBOutlet for the barButton, why not just set the title in the storyboard? I think this is the easiest way unless you have some other reason for doing it programmatically.

网友答案:

Change title or image and then resign it back to navigationItem:

class AnotherViewController: UIViewController {

    @IBOutlet weak var myBarButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let barButton = myBarButton
        barButton?.title = "Anther Title"
        navigationItem.rightBarButtonItem = barButton

    }
}

Apple document: https://developer.apple.com/reference/uikit/uibaritem/1616412-title

You should set this property before adding the item to a bar. The default value is nil.

网友答案:

When I try this, it works. Maybe there is a bug with Xcode, delete your button and connections then try again.

class ViewController: UIViewController {

   @IBOutlet weak var barButton: UIBarButtonItem!
   override func viewDidLoad() {
       super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
       barButton.title = "MyButton"
}
网友答案:

Try this instead

@IBOutlet weak var barButton: UIBarButtonItem! {
  didSet {
    barButton.title = "AB"
 }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: