![](/img/trans.png)
[英]Can't add segmented control to toolbar via code using a UIBarButtonItem with a custom view
[英]Can't add UIBarButtonItem to toolbar
經歷了針對這個問題的每一個stackoverflow解決方案之后,它仍然令人沮喪地不適合我。
//UIBarButtonItem declaration
UIBarButtonItem* button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button Text"
style:UIBarButtonItemStyleBordered target:self action:@selector(myAction)];
//method 1
[self setToolbarItems:[NSArray arrayWithObjects: button1, nil] animated:YES];
//method 2
[self.navigationController.toolbar setItems:[NSArray arrayWithObject:button1]];
//method 3
self.navigationController.toolbarItems = [NSArray arrayWithObject:button1];
//displaying toolbar
[self.navigationController setToolbarHidden:NO];
上述方法都不適用於在工具欄上顯示按鈕 - 我得到的只是一個空白工具欄。 有什么明顯的東西我在這里不見了嗎?
移動
//UIBarButtonItem declaration
UIBarButtonItem* button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button Text"
style:UIBarButtonItemStyleBordered target:self action:@selector(myAction)];
//method 1
[self setToolbarItems:[NSArray arrayWithObjects: button1, nil] animated:YES];
//displaying toolbar
[self.navigationController setToolbarHidden:NO];
to viewDidAppear:(BOOL)animated
這是UINavigationController獲取它管理的UIViewController工具欄項的點。
采用
self.toolbarItems=[NSArray arrayWithObject:button1]
使用Swift 3 / iOS 10,在最簡單的情況下,您的導航控制器將只包含一個視圖控制器,您可以使用下面的代碼,以便使用包含條形按鈕項的工具欄顯示視圖控制器:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Show navigation controller’s built-in toolbar
navigationController?.setToolbarHidden(false, animated: false)
// Set the view controller toolbar items
let items = [UIBarButtonItem(title: "Button Text", style: .plain, target: nil, action: nil)]
setToolbarItems(items, animated: false)
}
}
但是,如果您計划在導航控制器的堆棧中安裝多個視圖控制器,則必須在viewWillAppear()
和viewWillDisappear()
中調用UINavigationController
的setToolbarHidden(_:animated:)
方法,以便正確顯示或隱藏導航控制器的內置工具欄:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Set the view controller toolbar items
let items = [UIBarButtonItem(title: "Button Text", style: .plain, target: nil, action: nil)]
setToolbarItems(items, animated: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Show navigation controller’s built-in toolbar
navigationController?.setToolbarHidden(false, animated: false)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Hide navigation controller’s built-in toolbar
navigationController?.setToolbarHidden(true, animated: false)
}
}
對於那些尋找Swift版本的人,試試這個:
let someVC: UIViewController = ...
let someButton: UIBarButtonItem = ...
someVC.setToolbarItems([someButton], animated: true)
UINavigationController.toolbar
屬性文檔明確說明了應該使用哪個API來設置工具欄項:
管理此工具欄的內容是通過與此導航控制器關聯的自定義視圖控制器完成的。 對於導航堆棧上的每個視圖控制器,您可以使用
UIViewController
的setToolbarItems:animated:
方法分配一組自定義工具欄項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.