當(dāng)有需求為在導(dǎo)航欄左右兩邊自定義按鈕時,如果使用了以下做法,那么在iOS 11上就會出現(xiàn)問題:
-(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設(shè)置約束而不是設(shè)置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設(shè)置約束
然后在iOS11上運行
優(yōu)化后iOS11運行截圖
??????