UIBarButtonItem remove Back Button Title - iOS 11

谁说我不能喝 提交于 2019-12-05 14:12:14

The other way is to set UINavigationControllerDelegate for your navigationController and erase the title in its function.

class NoBackButtonTitleNavigationDelegate: UINavigationControllerDelegate {

    func navigationController(
        _ navigationController: UINavigationController,
        willShow viewController: UIViewController,
        animated: Bool
    ) {
        viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
    }
}

Use this code,

var newBackButton = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(self.back))
navigationItem?.leftBarButtonItem = newBackButton 

Create Navigation controller class as below. Assign this "CustomNavViewController" to UINavigationController in your StoryBoard

class CustomNavViewController: UINavigationController,UINavigationControllerDelegate 
{


override func viewDidLoad() {
    super.viewDidLoad()

    self.delegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func navigationController(
    _ navigationController: UINavigationController,
    willShow viewController: UIViewController,
    animated: Bool
    ) {
    viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
}

}

So, no need to do it in every viewControllers. At last remove below line from AppDelegate class if present,

UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), for:UIBarMetrics.default)

Instead of moving title vertically you can move horizontally. Also in case the title is long you can make its color transparent. Works just fine me:

let barButtonItemAppearance = UIBarButtonItem.appearance()
    barButtonItemAppearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.clear], for: .normal)
    barButtonItemAppearance.setBackButtonTitlePositionAdjustment(UIOffsetMake(-200, 0), for:UIBarMetrics.default)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!