我试图在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)
最佳答案
这段代码是错误的:
self.navigationController?.navigationItem.setRightBarButtonItems(
[rightBarButtonItemDelete, rightBarButtonItemEdit] as [AnyObject], animated: true)
您没有设置导航控制器的
navigationItem
;您设置navigationItem
。另外,[AnyObject]
东西也是不必要的。所以:self.navigationItem.setRightBarButtonItems(
[rightBarButtonItemDelete, rightBarButtonItemEdit], animated: true)
但是,请注意,仅当您的视图控制器是UINavigationController的子级时,该方法才有效。设置视图控制器的
navigationItem
只会在这种情况下自动填充导航栏。如果您不在那种情况下(即,如果您的界面中只有一个“松散”的导航栏),则需要手动填充导航栏(通过设置其navigationItem
)。(另外,请注意,如果没有
"me44.png"
图像,则可能是您的代码正在运行,但您什么都没看到。)关于ios - setRightBarButtonItems不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31142890/