Einzelheiten
- Xcode Version 10.2.1 (10E1001), Swift 5
Lösung
1. Erstellen Sie eine benutzerdefinierte Klasse des UINavigationController
import UIKit
class NavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
}
}
extension NavigationController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController.navigationItemBackButtonTextIsHidden {
viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
}
}
2. Fügen Sie die UIViewController-Erweiterung hinzu
import UIKit
extension UIViewController {
@objc var navigationItemBackButtonTextIsHidden: Bool { return false }
}
3. Aktualisieren Sie Ihre ViewController-Klasse
import UIKit
class ViewController: UIViewController {
override var navigationItemBackButtonTextIsHidden: Bool { return true }
}
Vollständige Probe
import UIKit
// MARK: - ViewController
class ViewController: UIViewController {
var screenCounter = 1
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationItem()
}
override var navigationItemBackButtonTextIsHidden: Bool { return (screenCounter % 2) == 0 }
}
extension ViewController {
private func setupNavigationItem() {
navigationItem.title = "VC \(screenCounter)"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "push", style: .plain, target: self, action: #selector(pushBarButtonTouchedUpInside))
}
@objc func pushBarButtonTouchedUpInside(button: UIBarButtonItem) {
guard let navigationController = navigationController else { return }
let viewController = ViewController()
viewController.screenCounter = screenCounter + 1
viewController.view.backgroundColor = .white
navigationController.pushViewController(viewController, animated: true)
}
}
// MARK: - NavigationController
class NavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
}
}
extension NavigationController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController.navigationItemBackButtonTextIsHidden {
viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
}
}
// MARK: - UIViewController extension
extension UIViewController {
@objc var navigationItemBackButtonTextIsHidden: Bool { return false }
}
Ergebnis