Client error attempting to change layout margins of a private view

 

从 iOS 11 开始,UINavigationBar 使用了自动布局,左右两边的按钮到屏幕之间会有 16 或 20 的边距。

为了避免点击到间距的空白处没有响应,通常做法是:定义一个 UINavigationBar 子类,重写 layoutSubviews 方法,在此方法里遍历 subviews 获取 _UINavigationBarContentView,并将其 layoutMargins 设置为 UIEdgeInsetsZero

 

- (void)layoutSubviews {
    [super layoutSubviews];

    for (UIView *subview in self.subviews) {
        if ([NSStringFromClass([subview class]) containsString:@"_UINavigationBarContentView"]) {
            subview.layoutMargins = UIEdgeInsetsZero;
            break;
        }
    }
}

 

然而,这种做法在 iOS 13 中会导致崩溃,崩溃信息如下:

 

Client error attempting to change layout margins of a private view

  

试图更改私有视图的布局边距时出现错误

 

解决方案:

使用设置 frame 的方式,让 _UINavigationBarContentView 向两边伸展,从而抵消两边的边距

 

- (void)layoutSubviews { [super layoutSubviews]; for (UIView *subview in self.subviews) { if ([NSStringFromClass([subview class]) containsString:@"_UINavigationBarContentView"]) { if ([UIDevice currentDevice].systemVersion.floatValue >= 13.0) { UIEdgeInsets margins = subview.layoutMargins; subview.frame = CGRectMake(-margins.left, -margins.top, margins.left + margins.right + subview.frame.size.width, margins.top + margins.bottom + subview.frame.size.height); } else { subview.layoutMargins = UIEdgeInsetsZero; } break; } } } 

 

 

你可能感兴趣的:(Client error attempting to change layout margins of a private view)