如何创建一个中间为红色的按钮呢 ?比如如图的按钮。
因为 tabBar 是 readonly 只读属性,所以不能使用下方的创建方式来自定义tabbar.
@property(nonatomic,readonly) UITabBar *tabBar NS_AVAILABLE_IOS(3_0); // Provided for -[UIActionSheet showFromTabBar:]. Attempting to modify the contents of the tab bar directly will throw an exception. // 不能使用这句话进行 创建自定义tabBar,因为 tabBar 是 只读属性。 self.tabBar = [[LTabBar alloc] init];
这个时候就可以使用KVC. 看下面的代码:
[self setValue:[[LTabBar alloc] init] forKeyPath:@"tabBar"];
LTabBar 是你创建的一个继承制 “UITabBar” 的类的类名。在 “LTabBar.m" 中写 下面的代码:
#import "LTabBar.h" @interface LTabBar() /** 发布按钮 */ @property (nonatomic, weak) UIButton *publishButton; @end @implementation LTabBar - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { UIButton *publishButton = [UIButton buttonWithType:UIButtonTypeCustom]; [publishButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal]; [publishButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted]; [self addSubview:publishButton]; self.publishButton = publishButton; } return self; } - (void)layoutSubviews { [super layoutSubviews]; // 设置发布按钮的frame self.publishButton.bounds = CGRectMake(0, 0, self.publishButton.currentBackgroundImage.size.width, self.publishButton.currentBackgroundImage.size.height); self.publishButton.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5); // 设置其他UITabBarButton的frame CGFloat buttonY = 0; CGFloat buttonW = self.frame.size.width / 5; CGFloat buttonH = self.frame.size.height; NSInteger index = 0; for (UIView *button in self.subviews) { // if (![button isKindOfClass:NSClassFromString(@"UITabBarButton")]) continue; if (![button isKindOfClass:[UIControl class]] || button == self.publishButton) continue; // 计算按钮的x值 CGFloat buttonX = buttonW * ((index > 1)?(index + 1):index); button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH); // 增加索引 index++; } } @end