How do I create (alloc/initwithImage) a UIBarButtonItem?
Is this the proper way to allocate and initialize a UIBarButton item with an image?
UIBarButtonItem *barBtn = [[UIBarButtonItem alloc]initWithImage:@"back_topbtn.png" style:UIBarButtonItemSt开发者_运维技巧yleDone target:nil action:nil];
No this not correct way, you are not using image object you are putting your image name here.so this shows a warning to you
UIBarButtonItem *barBtn = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_topbtn.png"] style:UIBarButtonItemStyleDone target:nil action:nil] autorelease];
this is the correct way to use it, also this is not more than an image when you are not declaring any action. so declare any action(use selector).
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *btnImg = [UIImage imageNamed:@"some_image-name"];
[btn setImage:btnImg forState:UIControlStateNormal];
btn.frame = CGRectMake(0, 0, btnImg.size.width, btnImg.size.height);
[btn addTarget:self action:@selector(whatever) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
The correct approach is to use an UIImage. It makes sense to do this in your - initWithNibName:bundle:
method.
Here is en example to add an image button to the right. Note that myButtonTapped:
will be called when the button is tapped, be sure to implement it.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = @"My title";
UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"myimage.png"] style:UIBarButtonItemStylePlain target:self action:@selector(myButtonTapped:)];
self.navigationItem.rightBarButtonItem = myButton;
[myButton release];
}
return self;
}
精彩评论