丹丹的丹的专栏

在完成自定义tabbar之后,就可以进行下一步了,先来看下上次的运行图:

tabbar做到现在,可能有点晕了,因为有2层tabor以及button,下面就先来分析一下:

这张效果图的时候,是因为有2层的button叠加在一起了,

从左边(最底下)到右边(最上面一层),分别是:view,UITabBar(系统自带的tabor),customTabBar(自定义的tabbar),customButton(自定义的button),button(系统自带的tabor上面的button)。

正是因为这样,才会出现上面的红色的重叠的图。

后来我们把系统自带的UITabBar上面的button移除掉,即移除了最上层的button层。所以才会有现在的效果图。

接下来就是对按钮需要进行改变,标题位置等需要改。先把红色背景给去掉了。

标题看不到了,是因为都是白色的,不过仔细看还是能看到一点的。

那就开始修改button了,最后是封装tabbarbutton。

修改button:

@interface QLDTabBar ()@property (nonatomic, weak) UIButton *selectedButton;@end@implementation QLDTabBar-(instancetype)initWithFrame:(CGRect)frame{self = [super initWithFrame:frame];if (self) {self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithName:@"tabbar_background"]];}return self;}- (void) addTabBarButtonWithItem: (UITabBarItem *)item{//1.创建按钮,将button加载到QLDTabBar上UIButton *button = [[UIButton alloc] init];[self addSubview:button];//2.设置按钮的数据[button setTitle:item.title forState:UIControlStateNormal];[button setImage:item.image forState:UIControlStateNormal];[button setImage:item.selectedImage forState:UIControlStateSelected];[button setBackgroundImage:[UIImage imageWithName:@"tabbar_slider"] forState:UIControlStateSelected];//3.监听按钮的点击[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];}/** * 监听按钮点击事件(达到每次只能选中一个按钮) */- (void)buttonClick: (UIButton *)button{// 取消当前选中的按钮self.selectedButton.selected = NO;// 选中现在点击的按钮button.selected = YES;self.selectedButton = button;}

在这里改变了tabbar的背景,以及按钮选中的图片等,具体效果如下:

从上面运行图可以看大,title和image的摆放位置有问题,应该是上下的,而不是左右的,所以需要对button里面的一些方法进行重写,下面创建一个继承自UIButton的QLDTabBarButton:

然后在里面进行重写:

#define QLDTabBarButtonImageRatio 0.6#import "QLDTabBarButton.h"@implementation QLDTabBarButton/** * 重写imageRectForContentRect方法,改变图片的位置 */-(CGRect)imageRectForContentRect:(CGRect)contentRect{//为了能够达到效果,这里是使图片沾满一定的位置,这里的x,y是相对于button来说的//图片的宽度就是按钮宽度CGFloat imageW = contentRect.size.width;CGFloat imageH = contentRect.size.height * QLDTabBarButtonImageRatio;return CGRectMake(0, 0, imageW, imageH);}/** * 重写titleRectForContentRect方法,改变标题的位置 */-(CGRect)titleRectForContentRect:(CGRect)contentRect{//在button里面,x = 0,但是y就不是了CGFloat titleY = contentRect.size.height * QLDTabBarButtonImageRatio;CGFloat titleW = contentRect.size.width;CGFloat titleH = contentRect.size.height – titleY;return CGRectMake(0, titleY, titleW, titleH);}@end

再回到QLDTabBar.m中,将UIButton全部替换成QLDTabBarButton

这里就是让按钮的位置进行改变,变成上下,而不是左右,看一下效果图:

虽然有点丑,但是毕竟目的达到了,起码变成上下位了,那么下面就可以进行其他设置了,先来将button进行一下封装:

还是用item进行传值,button在设置图片、标题的时候都是通过item进行设置的,所以就可以用这个来进行封装,即button.item = item;

在QLDTabBarButton.h中进行申明:

@property (nonatomic, strong) UITabBarItem *item;

然后在.m文件中重写setItem方法:

通过重写item方法,可以改变button里面的item的属性

绊住的不仅是双脚,还有未来。

丹丹的丹的专栏

相关文章:

你感兴趣的文章:

标签云: