Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setRightBarButtonItems doesn't work

I am trying to have 2 buttons on the right of a UINavigationBar. Below is the source code. No error but there is no button either. It is a UIViewController, not a 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)
like image 519
Dustin Sun Avatar asked Jul 29 '26 17:07

Dustin Sun


1 Answers

This code is just wrong:

self.navigationController?.navigationItem.setRightBarButtonItems(
    [rightBarButtonItemDelete, rightBarButtonItemEdit] as [AnyObject], animated: true)

You do not set the navigation controller's navigationItem; you set your navigationItem. Also, the [AnyObject] thing is just unnecessary. So:

self.navigationItem.setRightBarButtonItems(
    [rightBarButtonItemDelete, rightBarButtonItemEdit], animated: true)

However, note that that works only if your view controller is the child of a UINavigationController. Setting a view controller's navigationItem populates a navigation bar automatically only in that situation. If you are not in that situation — i.e., if you just have a "loose" navigation bar in your interface — you need to populate your navigation bar manually (by setting its navigationItem).

(Also, note that if you have no "me44.png" image, it could be that your code is working but you just aren't seeing anything.)

like image 74
matt Avatar answered Aug 01 '26 11:08

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!