Remove text from Back button keeping the icon

前端 未结 29 2427
栀梦
栀梦 2020-11-28 23:26

I want to remove the text from the back button, but I want to keep the icon. I have tried

let backButton = UIBarButtonItem(title: \"\", style: UIBarButtonIt         


        
相关标签:
29条回答
  • 2020-11-29 00:16

    Sometimes its not working to change only the title color, in case when the title is long. Because it might shift the navigation bar title to the left. So to prevent it you might need to shift the bar button title horizontally in addition to make it transparent:

    let barButtonItemAppearance = UIBarButtonItem.appearance()
        barButtonItemAppearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.clear], for: .normal)
        barButtonItemAppearance.setBackButtonTitlePositionAdjustment(UIOffsetMake(-200, 0), for:UIBarMetrics.default)
    
    0 讨论(0)
  • 2020-11-29 00:16

    You can remove text from back button using a delegate method of UINavigationController.

    class CustomNavigationController: UINavigationController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.delegate = self
        }
    
    }
    
    extension CustomNavigationController: UINavigationControllerDelegate {
        
        func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
            viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: String(), style: .plain, target: nil, action: nil)
        }
        
    }
    
    0 讨论(0)
  • 2020-11-29 00:17

    Xcode 10, Swift 4+

    Similar answer to the others here but it is worth noting that if the text still isn't cleared, you have to click Space then Enter.

    0 讨论(0)
  • 2020-11-29 00:19

    The easiest way to do this programmatically is to set backBarButtonItem from the parent view controller (a controller that calls push).

    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
            navigationItem.backBarButtonItem = backBarButtonItem
        }
    }
    

    More detail here https://sarunw.com/posts/how-to-remove-text-from-uinavigationbar-back-button/

    0 讨论(0)
  • 2020-11-29 00:19

    In Xcode 9.2 with Swift, it worked like this:

    override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(true)
       navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
    
    0 讨论(0)
提交回复
热议问题