![](/img/trans.png)
[英]How to hide/disable/remove navigation bar back button or hide status bar from apple watch?
[英]How to disable back button in navigation bar
有沒有官方的方法來設置UIBarButtonItem.enabled
屬性? 我試圖在以前的控制器中設置一個 backButtonItem。 但已enabled
屬性被忽略。
更多在這個簡單的 示例項目中。
我不想像“制作自己的 leftBarButtonItem 並設置它的 alpha 之類的解決方案......”
編輯:我不想隱藏它,只能用變暗的顏色和禁用的用戶交互來禁用它。 這與禁用leftBarButtonItem
行為leftBarButtonItem
。
截至今天,無法使用enabled
屬性禁用后退按鈕。 除非您創建自定義項,否則backBarButtonItem
屬性將為nil
,即使這樣它也會忽略enabled
屬性。 有幾種(不令人滿意的)方法可以解決這個問題。
鑒於 Apple 忽略了enabled
屬性,這就是 Apple 希望您執行的操作。 就這么簡單
navigationItem.hidesBackButton = true
除非您有充分的理由,否則應該是首選方法。
您可以在整個導航欄上禁用用戶交互並對其進行着色以使后退按鈕顯示為禁用。
navigationController?.navigationBar.isUserInteractionEnabled = false
navigationController?.navigationBar.tintColor = UIColor.lightGray
不幸的是,這也會影響導航欄中的其他元素,因此,例如,如果右側有另一個欄按鈕項,則它可能不是一個選項。
leftBarButtonItem
不會忽略enabled
屬性,因此您可以創建自定義項目並在激活時手動觸發彈出。
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(ThisClass.backButtonTapped))
...
navigationItem.leftBarButtonItem?.isEnabled = false
func backButtonTapped() {
self.navigationController?.popViewController(animated: true)
}
但是,這不會具有帶前導三角形指示器的后欄按鈕樣式。
在您的 ViewController2.swift 類中添加以下代碼。
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.hidesBackButton = true;
}
它會隱藏你的后退按鈕。
如果你想隱藏它, UInavigationItem
有一個hidesBackButton
屬性。
我知道這是一個舊線程,但這可能對其他人有所幫助。 正如 hennes 所提到的,您不能再禁用后退按鈕。 相反,您需要禁用整個導航欄。
我采用的方法是禁用導航欄,然后將 0.5 alpha 應用於導航欄的子視圖。
在您的 ViewController 類中:
func changeBarButtons(alpha: CGFloat) {
navigationController?.navigationBar.subviews.forEach { firstViews in
firstViews.subviews.forEach { view in
if ["_UIButtonBarButton", "_UIButtonBarStackView"].contains(type(of: view).description()) {
view.alpha = alpha
}
}
}
}
func set(loading: Bool) {
let alpha: CGFloat = loading ? 0.5 : 1
navigationController?.navigationBar.isUserInteractionEnabled = !loading
changeBarButtons(alpha: alpha)
}
請記住,Apple 可以隨時更改類的名稱。 話雖如此,他們這樣做的可能性很小。 如果您不介意 View Controller 的標題淡出,則可以將 alpha 應用於所有子視圖,而無需檢查類名。
不要嘗試禁用您的自定義后退按鈕(不起作用),只需設置一個已禁用的新按鈕。 您可以通過UINavigationBar.backItem
屬性訪問上一個導航項。
// set disabled back button
let backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItem.Style.plain, target: nil, action: nil)
backButton.isEnabled = false
navigationController?.navigationBar.backItem?.backBarButtonItem = backButton
// disable pop gesture
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.