विवरण
- Xcode संस्करण 10.2.1 (10E1001), स्विफ्ट 5
उपाय
1. 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. UIViewController एक्सटेंशन जोड़ें
import UIKit
extension UIViewController {
@objc var navigationItemBackButtonTextIsHidden: Bool { return false }
}
3. अपने ViewController क्लास को अपडेट करें
import UIKit
class ViewController: UIViewController {
override var navigationItemBackButtonTextIsHidden: Bool { return true }
}
पूरा नमूना
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 }
}
परिणाम