iPhone – 无法看到我的导航栏自定义按钮,但它是可点击的

我想在导航栏中添加一个自定义按钮(右侧).

我的“viewDidLoad”函数中有以下代码:

UIButton *audioBtn = [[UIButton alloc] init];
[audioBtn setTitle:@"Play" forState:UIControlStateNormal];

UIImage *buttonImage = [UIImage imageNamed:@"play.png"];
[audioBtn setBackgroundImage:buttonImage forState:UIControlStateNormal];

[audioBtn addTarget:self action:@selector(toggleAudioPlayback:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:audioBtn];
self.navigationItem.rightBarButtonItem = button;

[audioBtn release];
[button release];

我在导航栏中看不到按钮,但是如果我点击右边(按钮应该在哪里),它会触发“toggleAudioPlayback”功能,所以唯一的问题是我没有看到按钮!

我尝试了不同的图像,设置背景颜色,没有任何作用……

顺便说一下,我在代码中的其他地方使用这个图像,我看到它(在自定义按钮上,但不在navigationBar中).

请帮帮我!

最佳答案 让您的生活更轻松,而不是自定义视图只需使用带有自定义图像的UIBarButtonItem:

    UIBarButtonItem *audioBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"play.png"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleAudioPlayback:)];
    self.navigationItem.rightBarButtonItem = audioBtn;
    [audioBtn release];

UPDATE

既然你已经表明你希望你的按钮没有边框,那么你需要使用一个CustomView,但是我已经修改了你的代码以使其工作(关键的区别在于框架的分配,设置为图像的大小,但您可以将其设置为自定义大小以使图像居中):

UIButton *audioBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *playImg = [UIImage imageNamed:@"play.png"];
[audioButton setBackgroundImage:playImg forState:UIControlStateNormal];
[audioButton setBackgroundImage:playImg forState:UIControlStateHighlighted];
audioBtn.frame = CGRectMake(0,0,playImg.size.width,playImg.size.height);
[audioBtn addTarget:self action:@selector(toggleAudioPlayback:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:audioBtn];
self.navigationItem.rightBarButtonItem = button;
[audioBtn release];
[button release];
点赞