How to add a UIBarButtonItem programmatically?

2019-05-23 00:56发布

what's the proper way to add a UIBarButtonItem programmatically? In my case I'm trying to add one to the rightBarButtonItem and I've been hopping round the controller hierarchy but I can't seem to get the button to show up anywhere.

Here's my current code:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationItem setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithImage:[[UIImage alloc] initWithContentsOfFile:@"Barcode-White.png"] style:UIBarButtonItemStylePlain target:self action:@selector(scanEquipment:)] autorelease]];
}

I'm hoping someone can guide me into the right direction. The controller I'm trying to invoke this from is 3 levels in. So, UITabBarController -> UIViewController (Settings, 1st level) -> UIViewController (Vehicle, 2nd level) -> UIViewController (Inventory, 3rd level).

Anyway, thanks in advance for any help!

1条回答
叛逆
2楼-- · 2019-05-23 01:37

[[UIImage alloc] initWithContentsOfFile:@"Barcode-White.png"] probably won't work. initWithContentsOfFile takes a complete path to an image file, not just a file name. That's probably the problem; it's returning nil, which is causing the whole button constructor to return nil.

(Also, you're leaking this image by calling an init method without a release or autorelease.)

Try [UIImage imageNamed:@"Barcode-White"] instead, which looks for an image file in the app's resources, and has the added bonus of only loading the image once and then caching it in memory no matter how many times it's called:

http://developer.apple.com/library/ios/documentation/uikit/reference/UIImage_Class/Reference/Reference.html#//apple_ref/occ/clm/UIImage/imageNamed:

Other than that, it looks like it should work...

Also, navigation bar items always have a style of UIBarButtonItemStyleBordered. Trying to set it to UIBarButtonItemStylePlain will be ignored by the system. (But shouldn't be the reason it's not working.)

查看更多
登录 后发表回答