รายละเอียด
- Xcode เวอร์ชัน 10.2.1 (10E1001), Swift 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
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)
}
}
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)
}
}
}
extension UIViewController {
@objc var navigationItemBackButtonTextIsHidden: Bool { return false }
}
ผลลัพธ์