简体   繁体   中英

UIBarButtonItem remove Back Button Title - iOS 11

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

I use above to remove the backButtonTitle prior to iOS 11. But on iOS 11 that is not properly working. Arrow shifts bit downwards. 在此输入图像描述 How to fix this?

Edit: Other way by erasing Title can solve my problem but my concern is why that old way is not working anymore.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM