user1898829
user1898829

Reputation: 3527

show title and image in navigation bar button

I would like to show the button and image in the navigation bar.

Using this

     let action = UIAction {  _ in }
    let image = UIImage(named: "logout")
    let doneButton = UIBarButtonItem(title: "Done", image: image, primaryAction: action, menu: menu)
    navigationItem.leftBarButtonItem = doneButton

Just shows the image without the title.

The documentation https://developer.apple.com/documentation/uikit/uibarbuttonitem/3600776-init Only indicates that if title is nil it would not be displayed.

I tried https://stackoverflow.com/a/54403576/1898829 same result https://stackoverflow.com/a/3903348/1898829 one loses a lot of default behaviour and cant use the uiaction with the new apis.

While I can definitely find a work around but any work around is less than ideal.

Upvotes: 0

Views: 920

Answers (1)

Thang Phi
Thang Phi

Reputation: 1882

UIBarButtonItem doesn't support both text and image in the same UIBarButtonItem. There are 3 approach to solve this problem:

  1. Make your self a custom navigation controller
  2. Make an image which combine both your text and your image
  3. Make your text and image into a custom view. UIBarButtonItem support a custom View. Check example below for how to use. You can customize the View both in coding or using autolayout view for your choice
let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 50)))
let gesture = UITapGestureRecognizer(target: self, action: #selector(tapInView))
view.addGestureRecognizer(gesture)
view.backgroundColor = .red
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: view)


@objc func tapInView() {
        print("tap")
}

Upvotes: 0

Related Questions