我使用以下代码在导航栏中创建了按钮:
UIBarButtonItem *myButtonEn = [[UIBarButtonItem alloc] initWithTitle:@"EN" style:UIBarButtonItemStyleDone target:self action:@selector(buttonEN:)];
我对此按钮的操作:
- (void) buttonEN:(id)sender {
NSLog(@"English language");
}
这很好但我必须更改背景和按钮的样式(下面的代码)。
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];
这正是我需要的,但我需要设置行动
[myButtonEn setTarget:self];
[myButtonEn setAction:@selector(buttonEN:)];
此代码编译时没有错误,但按钮没有响应。
有谁知道出了什么问题?
答案 0 :(得分:7)
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");
}
答案 1 :(得分:2)
您缺少action
和target
按钮
您可以使用
进行设置[myButtonEn setTarget:self];
[myButtonEn setAction:@selector(buttonEN:)];
答案 2 :(得分:1)
您可能想要更改此按钮的外观。
[[UIBarButtonItem appearance] setBackgroundImage:<doneBackgroundImage>
forState:UIControlStateNormal
style:UIBarButtonItemStyleDone
barMetrics:UIBarMetricsDefault];
答案 3 :(得分:0)
您无需为图像使用自定义视图, 尝试使用:
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:yourImage style:UIBarButtonItemStylePlain target:target action:@selector(selector)];