Change Width of a Uibarbuttonitem in a Uinavigationbar

Change width of a UIBarButtonItem in a UINavigationBar

One approach you might consider is creating a UIBarButtonItem by calling initWithCustomView:. This is not ideal in that you don't get "selected" states out of the box AND you have to composite your bordered background (if want that look) with your button image, but with that you can more directly specify a frame for your toolbar item. If you're using text for your title instead of images you may still need add in a background image as a subview. Anyway, I'm having the same problem right now and this code works for me:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button-image.png"]];
imageView.frame = CGRectMake(0, 0, 43, 30);

UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageView];

self.navigationItem.leftBarButtonItem = barButtonItem;

Right now this is the only way I know of restricting the auto-sizing of the UIBarButtonItems added to the UINavigationController's navigationItem.

Or try Maggie's solution, which is more thorough than mine.

Change width of a UIBarButtonItem in a UINavigationBar in swift

// Swift 3
let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
backButton.setBackgroundImage(UIImage(named: "img"), for: .normal)
backButton.addTarget(self, action: "action:", for: .touchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)

// Swift 2
let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
backButton.setBackgroundImage(UIImage(named: "img"), forState: .Normal)
backButton.addTarget(self, action: "action:", forControlEvents: .TouchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)

Change size of UIBarButtonItem (image) in Swift 3

In the end I did it like this and it worked:

let moreButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
moreButton.setBackgroundImage(UIImage(named: "ic_more_vert_3"), for: .normal)
moreButton.addTarget(self, action: #selector(TableViewController.handleMore), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: moreButton)

Answer from: Change width of a UIBarButtonItem in a UINavigationBar in swift

Change the width of an UIBarButtonItem

you cant. If you want custom width you will need to use initWithCustomView

Change the width of an UIBarButtonItem

you cant. If you want custom width you will need to use initWithCustomView

Resize UIBarButtonItem in code

You can't resize a UIBarButtonItem as you would a UIView. What you can do is change its width property.

UIBarButtonItem *b;
// Initialize and such ...
b.width = 150.0;

This should work for a Fixed Space Bar Button Item.



Related Topics



Leave a reply



Submit