Reputation: 275
I created button in navigation bar with this code:
UIBarButtonItem *myButtonEn = [[UIBarButtonItem alloc] initWithTitle:@"EN" style:UIBarButtonItemStyleDone target:self action:@selector(buttonEN:)];
My action for this button:
- (void) buttonEN:(id)sender {
NSLog(@"English language");
}
This works fine but I have to change background and button's style (code below).
UIImage *imageEN = [UIImage imageNamed:@"cys_lang_en.png"];
UIButton *buttonImgEN = [UIButton buttonWithType:UIButtonTypeCustom];
buttonImgEN.bounds = CGRectMake( 0, 0, imageEN.size.width, imageEN.size.height );
[buttonImgEN setImage:imageEN forState:UIControlStateNormal];
UIBarButtonItem *myButtonEn = [[UIBarButtonItem alloc] initWithCustomView:buttonImgEN];
This is axactly what I need, but I need to set action
[myButtonEn setTarget:self];
[myButtonEn setAction:@selector(buttonEN:)];
This code is compiled with no errors but button does not respond.
Does anyone know what is wrong?
Upvotes: 0
Views: 8339
Reputation: 398
try this..
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0.0f, 0.0f, 25.0f, 40.0f)];
[btn addTarget:self action:@selector(buttonEN:) forControlEvents:UIControlEventTouchUpInside];
[btn setImage:[UIImage imageNamed:@"cys_lang_en.png"] forState:UIControlStateNormal];
UIBarButtonItem *eng_btn = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.rightBarButtonItem = eng_btn;
}
-(void)buttonEN:(id)sender
{
NSLog(@"English language");
}
Upvotes: 7
Reputation: 17409
You are Missing action
and target
for button
You can set using,
[myButtonEn setTarget:self];
[myButtonEn setAction:@selector(buttonEN:)];
Upvotes: 2
Reputation: 1223
You might want to change apperance of this button.
[[UIBarButtonItem appearance] setBackgroundImage:<doneBackgroundImage>
forState:UIControlStateNormal
style:UIBarButtonItemStyleDone
barMetrics:UIBarMetricsDefault];
Upvotes: 1
Reputation: 19869
You don't need to use custom view for image, Try to use:
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:yourImage style:UIBarButtonItemStylePlain target:target action:@selector(selector)];
Upvotes: 0