0

我使用以下代码在导航栏中创建了按钮:

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:)];

此代码编译时没有错误,但按钮没有响应。

有谁知道出了什么问题?

4

4 回答 4

7

试试这个..

- (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");     
}
于 2013-09-17T09:37:07.463 回答
2

你失踪了actiontarget按钮

您可以设置使用,

[myButtonEn setTarget:self];
[myButtonEn setAction:@selector(buttonEN:)];
于 2013-09-17T09:04:37.557 回答
1

您可能想要更改此按钮的外观。

[[UIBarButtonItem appearance] setBackgroundImage:<doneBackgroundImage>
                                            forState:UIControlStateNormal
                                               style:UIBarButtonItemStyleDone
                                          barMetrics:UIBarMetricsDefault];
于 2013-09-17T08:57:14.680 回答
0

您不需要对图像使用自定义视图,尝试使用:

UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:yourImage style:UIBarButtonItemStylePlain target:target action:@selector(selector)];
于 2013-09-17T08:56:26.437 回答