如果设置tabBarItem.image
的时候,就是一张包括文字的图片,如图

结果就会偏上,底下留白是文字的位置:

此时可以继承自
UITabBar
,重写- (void)layoutSubviews
方法调整UITabBarButton
的y
位置达到正常显示的效果。代码如下
- (void)layoutSubviews
{
[super layoutSubviews];
// 遍历所有的button
for (UIView *tabBarButton in self.subviews) {
// 如果不是UITabBarButton, 直接跳过
if (![tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) continue;
// 根据索引调整位置
tabBarButton.mj_y = 7;
}
}
但是如果在NavigationController
的第三级界面起任一界面,执行
[self.navigationController popToRootViewControllerAnimated:YES];
会出现对tabbar中图片的调整失效
了。
我的解决办法是:
不使用KVC重写方法调整位置,改变图片的尺寸解决这个问题,将图片的高度调高。因为tabbar的高度固定,那么图片高了,文字的位置就会压缩。
将图片尺寸调高的代码:
- (UIImage *)tabbarImage:(UIImage *)image
{
CGFloat addValue = 10.0;
// 开启图形上下文
UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width, image.size.height+addValue), NO, 0.0);
// 将图片画上去
[image drawInRect:CGRectMake(0, addValue, image.size.width, image.size.height)];
// 获得图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 结束图形上下文
UIGraphicsEndImageContext();
return newImage;
}
网友评论