iOS 11IOS开发者学习笔记iOS项目实践中的学习

iOS--iOS11适配之navigationItem的大小问题

2017-09-05  本文已影响135人  阿木马克

当有需求为在导航栏左右两边自定义按钮时,如果使用了以下做法,那么在iOS 11上就会出现问题:

-(void)initRightButton{
    UIImage *issueImage = [UIImage imageNamed:@"icon_collection_un"];
    _collectionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _collectionButton.frame = CGRectMake(0, 0, 20, 20);
    [_collectionButton setBackgroundImage:issueImage forState:UIControlStateNormal];
    _collectionButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [_collectionButton addTarget:self action:@selector(changeCollectionState) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_collectionButton];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
}
iOS10运行截图 iOS11运行截图

解决办法:
给button设置约束而不是设置frame

UIImage *issueImage = [UIImage imageNamed:@"icon_collection_un"];
    _collectionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    NSLayoutConstraint * widthConstraint = [NSLayoutConstraint constraintWithItem:_collectionButton
                                                                        attribute: NSLayoutAttributeWidth
                                                                        relatedBy: NSLayoutRelationEqual
                                                                           toItem: nil
                                                                        attribute: NSLayoutAttributeNotAnAttribute
                                                                       multiplier: 1
                                                                         constant: 20];
    NSLayoutConstraint * heightConstraint = [NSLayoutConstraint constraintWithItem:_collectionButton
                                                                         attribute: NSLayoutAttributeHeight
                                                                         relatedBy: NSLayoutRelationEqual
                                                                            toItem: nil
                                                                         attribute: NSLayoutAttributeNotAnAttribute
                                                                        multiplier: 1
                                                                          constant: 20];
    [_collectionButton addConstraint:widthConstraint];
    [_collectionButton addConstraint:heightConstraint];
    [_collectionButton setBackgroundImage:issueImage forState:UIControlStateNormal];
    [_collectionButton addTarget:self action:@selector(changeCollectionState) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_collectionButton];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
button设置约束

然后在iOS11上运行

优化后iOS11运行截图

👌👌👌

上一篇 下一篇

猜你喜欢

热点阅读