向 iOS7 中未显示的 UINavigationBar 添加 0.5 磅高度的子视图

Add a 0.5 point height subview to UINavigationBar not show in iOS7

我有一个 class 继承自 UINavigationBar,我想添加一个分隔线作为它的子视图来分隔导航栏和导航内容。

线条的高度定义如下。

#define SEPERATOR_LINE_HEIGHT (1.0f / [UIScreen mainScreen].scale)

我的代码:

@interface MyPopNavigationBar : UINavigationBar
@end

@implementation MyPopNavigationBar {
    UIView *separatorLine;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds = YES;
        self.translucent = NO;

        separatorLine = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.bounds) - SEPERATOR_LINE_HEIGHT, CGRectGetWidth(self.bounds), SEPERATOR_LINE_HEIGHT)];
        separatorLine.backgroundColor = [UIColor redColor];
        separatorLine.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        [self addSubview:separatorLine];
    }
    return self;
}

这在 iOS 6 和 iOS 8(所有 Retina)中都很好用,但我在 iOS 7(Retina,也是)!

iOS 6 & 8:

iOS 7:

此外,当我尝试将分隔线高度设置为精确 1 时,它在所有 iOS 版本中都显示。

separatorLine = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.bounds) - 1, CGRectGetWidth(self.bounds), 1)];

怎么了?

我自己解决了这个问题。这是 autoresizingMask 的错。我强烈怀疑这是 iOS7.

的错误

我在 lldb 中打印了 recursiveDescription,却发现 separatorLine 的高度在 iOS7 中自动调整为零!相比之下,iOS8.

中的值为0.5

所以,删除这一行:

separatorLine.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;

并在MyPopNavigationBarlayoutSubviews方法中再次设置框架使其正确:

- (void)layoutSubviews {
    [super layoutSubviews];
    separatorLine.frame = CGRectMake(0, CGRectGetHeight(self.bounds) - SEPERATOR_LINE_HEIGHT, CGRectGetWidth(self.bounds), SEPERATOR_LINE_HEIGHT);
}

然后该行显示在所有 iOS 版本中。