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

Jor*_*own 5 iphone objective-c uinavigationcontroller uibarbuttonitem toolbaritems

我不知道我做错了什么.文件名正确,样式设置为plain.但我得到了一个像我的图像大小的银行白盒子.我正在使用UINavigationController.

请帮忙,谢谢你提前谢谢.

**仅供参考我对目标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];
Run Code Online (Sandbox Code Playgroud)

Jor*_*own 9

它创建白色蒙版的原因是因为UIToolBar默认情况下不允许使用彩色图像.实现此目的的方法是创建一个UIImage然后分配UIButton给该图像.然后创建一个UIBarButton使用initWithCustomViewUIButton作为自定义视图.

码:

     //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];
Run Code Online (Sandbox Code Playgroud)