简体   繁体   中英

Swift - How to hide back button in navigation item?

Right now I have two view controllers. My problem is I don't know how to hide the back button after transitioning to the second view controller. Most references that I found are in Objective-C. How do I code it in Swift?

Hide back button code in Objective-C

[self.navigationItem setHidesBackButton:YES animated:YES];

根据UINavigationItem文档

self.navigationItem.setHidesBackButton(true, animated: true)

In case you're using a UITabBarController :

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.tabBarController?.navigationItem.hidesBackButton = true
}

Swift

// remove left buttons (in case you added some)
 self.navigationItem.leftBarButtonItems = []
// hide the default back buttons
 self.navigationItem.hidesBackButton = true

这也可以在 UINavigationController 类文档中找到:

navigationItem.hidesBackButton = true

放在viewDidLoad方法中

navigationItem.hidesBackButton = true 

这在 Swift 5 中对我很有用,只需将其添加到您的 viewDidLoad()

self.navigationItem.setHidesBackButton(true, animated: true)

Here is a version of the answer in

Swift 5

that you can use it from the storyboard:

 // MARK: - Hiding Back Button extension UINavigationItem { /// A Boolean value that determines whether the back button is hidden. /// /// When set to `true`, the back button is hidden when this navigation item /// is the top item. This is true regardless of the value in the /// `leftItemsSupplementBackButton` property. When set to `false`, the back button /// is shown if it is still present. (It can be replaced by values in either /// the `leftBarButtonItem` or `leftBarButtonItems` properties.) The default value is `false`. @IBInspectable var hideBackButton: Bool { get { hidesBackButton } set { hidesBackButton = newValue } } }

Every navigation item of a view controller will have this new property in the top section of attributes inspector

self.navigationItem.setHidesBackButton(true, animated: false)

Try with below code in viewWillAppear method.

self.navigationItem.setHidesBackButton(true, animated: true)

Read below link for more support. https://developer.apple.com/documentation/uikit/uinavigationcontroller/customizing_your_app_s_navigation_bar

在 SwiftUI 中

.navigationBarBackButtonHidden(true)

put the below code in viewWillAppear method.

navigationItem.hidesBackButton = true

You may try with the below code

override func viewDidAppear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}

在此处输入图像描述

Go to attributes inspector and uncheck show Navigation Bar to hide back button.

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