使用 UIBarButtonItem 将图像添加到工具栏时出现问题,显示空白白框而非图像。

5

我不确定我的做法哪里出了问题。文件名是正确的,样式设置为纯文本。但是我得到了一个大小与我的图像相同的白色空白框。我正在使用UINavigationController。

请帮忙解决,非常感谢。

**FYI 我对objective c有点陌生,所以别太苛刻了。 ;)

 UIBarButtonItem *toolbarChannelGuideButton = [[UIBarButtonItem alloc]
     initWithImage:[UIImage imageNamed:@"channel-guide-button.png"]
     style:UIBarButtonItemStylePlain
     target:self
     action:@selector(action:)];


self.toolbarItems = [NSArray arrayWithObjects:toolbarChannelGuideButton, nil];
[toolbarChannelGuideButton release];
3个回答

9

它创建白色遮罩的原因是默认情况下UIToolBar不允许在其上使用彩色图像。实现这一点的方法是创建一个UIImage,然后将UIButton分配给该图像。接着,使用initWithCustomView并以UIButton作为自定义视图来创建UIBarButton

代码:

     //Load the image   
     UIImage *buttonImage = [UIImage imageNamed:@"your-image.png"];

     //create the button and assign the image
     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
     [button setImage:buttonImage forState:UIControlStateNormal];

     //sets the frame of the button to the size of the image
     button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);

     //creates a UIBarButtonItem with the button as a custom view
     UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];



     self.toolbarItems = [NSArray arrayWithObjects:customBarItem, nil];
     [customBarItem release];

UIButtonTypeCustom 对我很有用。我之前使用的是 roundedrect。 - coolcool1994

1
从iOS 7开始,您可以使用以下内容:
 UIImage *image = [[UIImage imageNamed:@"myImage.png"];
 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
 UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(YOUR_METHOD:)];

-1

channel-guide-button.png属于这个项目吗?

你可以像这样拆分:

UIImage *image = [UIImage imageNamed:@"channel-guide-button.png"];
NSLog(@" image = %p", image);
UIBarButtonItem *toolbarChannelGuideButton = [[UIBarButtonItem alloc]
     initWithImage:image
     style:UIBarButtonItemStylePlain
     target:self
     action:@selector(action:)];

或者只需检查您的项目;-)


我检查了我的项目,是存在里面的。我还运行了一个NSLog,它显示了一个低级别的数字。 - Jordan Brown
图像 = 0x6b45340 是控制台中显示的内容。 - Jordan Brown
好吧。顺便说一句,我通常使用initWithCustomView:创建UIBarButtonItem,并传入带有相关图像的UIButton。我明天会发布代码示例。 - westsider
无需发布示例,我已经想到了。谢谢您的帮助! - Jordan Brown
现在我只是在尝试弄清楚如何将其居中放置在工具栏上。 - Jordan Brown
你的真实姓名是什么,西区居民? - Jordan Brown

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接