Search code examples
swiftuikituinavigationbar

UIKit: Adding text to NavigationBar


I'm diving into UIKit and feel some misunderstanding after using SwiftUI. By following course from Paul Hudson there is some challenges in the end of the project. One of this it's try showing the player’s score in the navigation bar. I try to solve this case but closest solution that I found from Apple's documentation it's:

let scoreButton = UIBarButtonItem(title: NSLocalizedString("Score: \(score)", comment: ""),
                                        style: .done,
                                        target: self,
                                        action: nil)
navigationItem.rightBarButtonItem = scoreButton

But I think adding Button instead of simple Text is unnecessary, I don't need button behavior. Trying to add UITextView() to NavigationBar from storyboard did't work out...

Question: how to add text(better programmatically) to Navigation Bar? something like .toolbarItem with ToolbarItemPlacement: .navigationBarTrailing in SwiftUI. Is it possible or it's a UIKit restriction using only rightBarButtonItem?

enter image description here


Solution

  • I found solution how to add text to NavBar and yes it's restriction of UIKit thats you have to use UIBarButtonItem

    let scoreView = UILabel()
    scoreView.text = "Score: \(score)"
    let scoreButton = UIBarButtonItem(customView: scoreView)
    navigationItem.rightBarButtonItem = scoreButton