在iOS 11之前,我们自定义的导航按钮一般是这样
NSMutableArray * items = [[NSMutableArray alloc] init];
NSInteger i = 0;
for (NSString * imageName in imageNames) {
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
btn.frame = CGRectMake(0, 0, 30, 30);
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
if (isLeft) {
[btn setContentEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
}else{
[btn setContentEdgeInsets:UIEdgeInsetsMake(0, 5, 0, -5)];
}
btn.tag = [tags[i++] integerValue];
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:btn];
[items addObject:item];
}
if (isLeft) {
self.navigationItem.leftBarButtonItems = items;
} else {
self.navigationItem.rightBarButtonItems = items;
}
但是我们到iOS 11后,发现按钮使用图片后会出现变形拉伸等问题,除非使用正确大小的图片,显然,这个正确大小的图片是不好轻易控制的。
那么这个问题为什么会出现?
这是因为iOS 11的UIBarButtonItem使用了自动布局。
那么我们怎么解决呢?
如果是在xcode9,我们可以给这个图像的按钮一个宽高约束。
NSMutableArray * items = [[NSMutableArray alloc] init];
NSInteger i = 0;
for (NSString * imageName in imageNames) {
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
btn.frame = CGRectMake(0, 0, 30, 30);
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
if (isLeft) {
[btn setContentEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
}else{
[btn setContentEdgeInsets:UIEdgeInsetsMake(0, 5, 0, -5)];
}
btn.tag = [tags[i++] integerValue];
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:btn];
[items addObject:item];
//iOS 11图片约束,针对此约束最好做一个iOS 11的版本判断,让他只在iOS 11上实行
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(30, 30));
}];
}
if (isLeft) {
self.navigationItem.leftBarButtonItems = items;
} else {
self.navigationItem.rightBarButtonItems = items;
}
网友评论