iOS11适配 - 导航栏

好久没写东西,转战,重装出发吧。

项目里用了两种自定义返回键,发现在Xcode9+iOS11上歇菜了,少不了折腾一番。

A. 自定义的navigationItem.backBarItem:

    UIImage *backButtonImage = [UIImage imageNamed:@"icon_back"];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    [backItem setBackButtonBackgroundImage:[backButtonImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backButtonImage.size.width, 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    self.navigationItem.backBarButtonItem = backItem;

点进二级页就华丽的crash了,苹果就是任性。。

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', 
reason: '_UIButtonBarButtonVisualProviderIOS cannot have a background without any content'

意思是必须设image or title,好吧,给它个@""。然后有个讨厌的蓝色箭头一直存在,而这货是根据tintColor来绘制的,所以你遍历bar层级把对应的view.hidden=YES没用,它还是会多次绘制展示。最终灵光一闪,把tintColor设成clearColor,so加上这两句就O了~

    [backItem setTitle:@""];
    backItem.tintColor = [UIColor clearColor];

当然,用leftItem+FDFullscreenPopGesture的同学可以跳过这段。

B. 自定义的navigationItem.leftBarItem

    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setFrame:CGRectMake(0, 0, 44, 44)];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                     initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -15;
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, leftBarItem, nil];

现象是箭头距离屏幕会比较长的留白。一开始以为negativeSpacer要设成0,其实没用。只用@[leftBarItem]也一样。遍历view层级改结构也是坑。google上的 老外 说iOS11导航栏默认开启autolayout,所以想让setFrame生效,自然就是把它关了呗

    leftButton.translatesAutoresizingMaskIntoConstraints = NO;
    [leftButton setContentEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];

rightItem同理。

坑未完待续。

你可能感兴趣的:(iOS11适配 - 导航栏)