我目前正在为 iPad 优化应用程序,并希望使用带有图像的 UIBarButtonItem 来呈现弹出框。如果我使用带有标题的按钮,我目前拥有的代码效果很好,但我更喜欢使用我自己的图像或 UIBarButtonSystemItem 提供的图像之一。如果我根本不设置按钮的标题,它根本不会出现。如果我设置标题和图像,我会在真实硬件上获得标题,但图像会显示在模拟器上。使用 UIBarButtonSystemItem,我得到了我想要的按钮,但它也出现在横向模式下(它不应该这样做,因为我对横向使用了拆分视图)。
使用 setImage、setTitle 的任意组合或将按钮初始化为系统预设均无效。当检测到旋转到横向时,我还尝试将系统预设的按钮设置为 nil,但它仍保留在屏幕上。我不确定如何从这里开始,但我真的很想避免在这个按钮上使用字符串,而且我很想知道为什么会这样。
这是代码:
#pragma mark Split view handling
-(void)splitViewController:(UISplitViewController *)svc
willHideViewController:(UIViewController *)aViewController
withBarButtonItem:(UIBarButtonItem *)barButtonItem
forPopoverController:(UIPopoverController *)pc
{
//If this bar button item doesn't have a title, it won't appear at all.
[barButtonItem setTitle:@"-"];
//barButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:[barButtonItem target] action:[barButtonItem action]];
[barButtonItem setImage:[UIImage imageNamed:@"listing.png"]];
//Take this bar button item and put it on the left side of our nav item
[[self navigationItem] setLeftBarButtonItem:barButtonItem];
self.popoverController = pc;
}
-(void)splitViewController:(UISplitViewController *)svc
willShowViewController:(UIViewController *)aViewController
invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
//Remove the bar button item from our navigation item.
//We'll double check that it's the correct button, even though we know it is.
if(barButtonItem == [[self navigationItem] leftBarButtonItem]){
[[self navigationItem] setLeftBarButtonItem:nil];
}
self.popoverController = nil;
}
更新:
我将此添加到我的 viewDidLoad 中:
customButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"listing.PNG"]]];
customButtonItem.style = UIBarButtonItemStyleBordered;
并将 willHideViewController 更新为:
-(void)splitViewController:(UISplitViewController *)svc
willHideViewController:(UIViewController *)aViewController
withBarButtonItem:(UIBarButtonItem *)barButtonItem
forPopoverController:(UIPopoverController *)pc
{
//If this bar button item doesn't have a title, it won't appear at all
customButtonItem.target = barButtonItem.target;
customButtonItem.action = barButtonItem.action;
barButtonItem = customButtonItem;
[barButtonItem setTitle:@""];
//barButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:[barButtonItem target] action:[barButtonItem action]];
//[barButtonItem setImage:[UIImage imageNamed:@"listing.png"]];
//Take this bar button item and put it on the left side of our nav item
[[self navigationItem] setLeftBarButtonItem:barButtonItem];
self.popoverController = pc;
}
这导致图像在我想要的时间/位置显示,但按钮没有边框(尽管我将其设置为)并且不显示弹出框。