9

我在 iPhone 应用程序中有一个导航栏,其中有一个自定义 UIBarButtonItems:

UIBarButtonItem* homePersonButton = [[UIBarButtonItem alloc]
       initWithImage:[UIImage imageNamed:@"homePerson.png"]
               style:UIBarButtonItemStylePlain
              target:self action:@selector(showHomePerson)];

homePerson.png 为 20 x 18。

它在纵向模式下看起来不错,但在横向模式下,按钮上的 20x18 图像太高而不好看。看起来 iOS 在其标准按钮上做了一些工作,以在图像位于较薄的导航栏中时根据需要缩小图像。

处理这个问题的最佳方法是什么?

另一个例子是当我在导航栏的 titleView 中有一个自定义按钮时。当应用程序旋转时,我也需要它缩小。

提前感谢您能给我的任何指示!

4

3 回答 3

5

工具栏和导航栏图像的大小为 20 x 20,因此当您提供的图像不符合这些尺寸时,您将留给框架来调整/缩放您的图像,这会导致您的问题。将您的图像大小/缩放为 20x20,并且您的图像在纵向和横向中都应该看起来正确。

于 2010-11-09T22:40:40.783 回答
3

steipete 在评论中提到了这一点,但我觉得现在需要一个答案。从 iOS 5 开始,您可以使用UIBarButtonItem 初始化程序

- initWithImage:landscapeImagePhone:style:target:action:

只需将landscapeImagePhone图像设置为要在横向调整大小的图像的较小版本。

经过一些测试,我注意到 iPhone 确实缩小了导航栏,因此导航栏上的 UIBarButtonItems 缩小了,但 iPhone 6 Plus没有。6 Plus 似乎将导航栏保持在 44 像素的高度,而普通 iPhone 将其缩小到 32 像素。正因为如此,6 Plus 也没有使用landscapeImagePhone横屏。

我不仅使用较小尺寸的图像进行了测试,还使用landscapeImagePhone了完全不同的图像。图像在 6 Plus 上从未改变。


但是,从 iPhone 6 Plus 上的 iOS 9.2 开始,请注意以下几点:

此初始化程序的Apple 文档指出landscapeImagePhone

UIUserInterfaceIdiomPhone 惯用语中横向栏中的项目要使用的图像。

从 iOS 9.2 开始,6 Plus 确实报告UIUserInterfaceIdiomPhone纵向和横向。之前,6 Plus 曾经是UIUserInterfaceIdiomUnspecified. 我不确定那是什么时候更新的。但是,既然是现在UIUserInterfaceIdiomPhone,根据文档,它landscapeImagePhone也应该适用于 6 Plus。

所以也许它对 UIUserInterfaceIdiom 的依赖不如对导航栏高度的依赖。我不确定。请注意,这种不一致将来可能会“修复”,因此会导致不同的行为。

于 2015-07-30T14:30:34.573 回答
0

我有类似的问题。现在我使用自定义类型来按钮。例如,这是我的 UIBarButtonItem 目录。您可以使用它来构建自定义栏按钮。

+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image highlightedImage:(UIImage *)highlightedImage     target:(id)target action:(SEL)action{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage: [image stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateNormal];
    button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height);
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    return barItem;
}

然后您可以在旋转时调整条形按钮自定义视图框架。

小费:

  1. 在旋转方法中,例如 willAnimateRotationToInterfaceOrientation,打印导航栏按钮项的自定义视图框架..,并获得您想要的正确框架(在纵向模式下),并且在横向模式下您可以看到框架不正确,我们需要修理它。
  2. 通过引用正确的框架值来修复横向栏按钮框架问题。

就我而言,我只是简单地修复了自定义视图的来源......例如

// adjust the navigation Item top, otherwise it is not proper set after rotation
_centralRootViewController.navigationItem.leftBarButtonItem.customView.top = 5;
_centralRootViewController.navigationItem.rightBarButtonItem.customView.top = 5;

注意:顶部是框架的 y。

于 2012-04-11T19:58:20.040 回答