MKodes
MKodes

Reputation: 81

Remove the back button text

Currently trying to remove the title of the previous VC on the back button. Following apple's documentation I have used:

let backBarButtton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backBarButtton

However the back button title does not disappear! The console says it's empty (""), but it's clearly still displayed to the user.

I do not want to use hacks such as setting the previous title of previous VC to "" however currently nothing else seems to be working. Any advice?

Upvotes: 0

Views: 276

Answers (3)

Dan O
Dan O

Reputation: 36

Try this:

self.navigationController?.navigationBar.topItem?.backBarButtonItem = backBarButtton

Your code changes the appearance of back button when other controller pushed above current one. But You need to modify back button on current controller.

See docs on backBarButtonItem:

When this navigation item is immediately below the top item in the stack, the navigation controller derives the back button for the navigation bar from this navigation item. When this property is nil, the navigation item uses the value in its title property to create an appropriate back button. If you want to specify a custom image or title for the back button, you can assign a custom bar button item (with your custom title or image) to this property instead. When configuring your bar button item, do not assign a custom view to it; the navigation item ignores custom views in the back bar button anyway.

Upvotes: 1

Mahsa Yousefi
Mahsa Yousefi

Reputation: 236

Try this function as extension of UINavigationController :

func setBackButtonTitle(_ title: String) {
    if self.navigationBar.topItem != nil {
        let leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(title: title, style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.backButtonAction))
        self.navigationBar.topItem?.backBarButtonItem = leftBarButtonItem
    } else {
        if self.navigationBar.backItem != nil {
            self.navigationBar.backItem?.title = title
        }
    }
}

Upvotes: 1

pikacode
pikacode

Reputation: 178

u can init it with a UIButton instead

let button = UIButton()
let item = UIBarButtonItem(customView: button)
navigationItem.backBarButtonItem = item

Upvotes: 0

Related Questions