我想在UINavigationBar
的右侧设置2个按钮。以下是源代码。没有错误,但也没有按钮。这是UIViewController
,而不是UINavigationViewController
let buttonEdit: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
buttonEdit.frame = CGRectMake(0, 0, 40, 40)
buttonEdit.setImage(UIImage(named:"me44.png"), forState: UIControlState.Normal)
buttonEdit.addTarget(self, action: "rightNavItemEditClick:", forControlEvents: UIControlEvents.TouchUpInside)
var rightBarButtonItemEdit: UIBarButtonItem = UIBarButtonItem(customView: buttonEdit)
let buttonDelete: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
buttonDelete.frame = CGRectMake(0, 0, 40, 40)
buttonDelete.setImage(UIImage(named:"me44.png"), forState: UIControlState.Normal)
buttonDelete.addTarget(self, action: "rightNavItemDeleteClick:", forControlEvents: UIControlEvents.TouchUpInside)
var rightBarButtonItemDelete: UIBarButtonItem = UIBarButtonItem(customView: buttonDelete)
// add multiple right bar button items
self.navigationController?.navigationItem.setRightBarButtonItems([rightBarButtonItemDelete, rightBarButtonItemEdit] as [AnyObject], animated: true)
//I also tried code below no luck either
self.navigationItem.setRightBarButtonItems([rightBarButtonItemDelete, rightBarButtonItemEdit] as [AnyObject], animated: true)
答案 0 :(得分:6)
这段代码错了:
self.navigationController?.navigationItem.setRightBarButtonItems(
[rightBarButtonItemDelete, rightBarButtonItemEdit] as [AnyObject], animated: true)
您没有设置导航控制器的navigationItem
;你设置你的 navigationItem
。此外,[AnyObject]
事情是不必要的。所以:
self.navigationItem.setRightBarButtonItems(
[rightBarButtonItemDelete, rightBarButtonItemEdit], animated: true)
但请注意,仅当您的视图控制器是UINavigationController的子级时才有效。设置视图控制器的navigationItem
仅在该情况下自动填充导航栏。如果您在那种情况下不 - 即,如果您的界面中只有一个“松散”的导航栏 - 您需要手动填充导航栏 (通过设置< em>它的 navigationItem
)。
(另请注意,如果您没有"me44.png"
图片,可能是您的代码正在运行,但您只是看到任何内容。)
答案 1 :(得分:0)
尽管之前已经说明了,但您可能没有看到添加到导航栏的按钮。对于Swift 3,请在 AppDelegate类中尝试此操作(注意 topItem ):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
window?.backgroundColor = UIColor.white
let navigationVC = UINavigationController(rootViewController: UIViewController())
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTodo))
navigationVC.navigationBar.topItem?.rightBarButtonItem = addButton
window?.rootViewController = navigationVC
window?.makeKeyAndVisible()
return true
}