当有需求为在导航栏左右两边自定义按钮时,如果使用了以下做法,那么在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;
}
解决办法:
给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;
然后在iOS11上运行
👌👌👌