iOS

UIBarButtonItem大小适配iOS11

2017-10-17  本文已影响1138人  Billlin

iOS11上如果在UIBarButtonItem的customView上添加红点或者其它的控件,那么通过customView的bounds设置宽高是无效的,而在系统版本iOS11以下的设备上运行是正常的。



在系统iOS11的设备上运行的效果

在系统iOS10的设备上运行的效果



造成原因

从iOS11开始UIBarButtonItem使用自动布局引擎。

解决办法

    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    rightButton.bounds = CGRectMake(0, 0, 22, 22);
    
#ifdef __IPHONE_9_0
    if ([rightButton respondsToSelector:@selector(widthAnchor)]) {
        [rightButton.widthAnchor constraintEqualToConstant:22].active = YES;
    }
    if ([rightButton respondsToSelector:@selector(heightAnchor)]) {
        [rightButton.heightAnchor constraintEqualToConstant:22].active = YES;
    }
#endif
    
    [rightButton setBackgroundImage:UIImageNamed(@"icon_message_normal.png")
                           forState:UIControlStateNormal];
    [rightButton setBackgroundImage:UIImageNamed(@"icon_message_pressed.png")
                           forState:UIControlStateHighlighted];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;

效果:



参考

Constraint a UIBarButtonItem's size in the navigaiton bar with iOS 11

Updating Your App for iOS 11

上一篇 下一篇

猜你喜欢

热点阅读