专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
添加加号按钮
- 目前效果:
- 中间缺少一个
加号按钮
在
CZTabBarController
的viewDidLoad
中 添加一个普通的UIViewController
作为tabbar controller
的子控制器来占位// 添加动态控制器 [self addChildViewController:[[CZHomeViewController alloc] init] title:@"动态" imageName:@"tabbar_icon_auth"]; // 添加与我相关控制器 [self addChildViewController:[[CZAboutMeViewController alloc] init] title:@"与我相关" imageName:@"tabbar_icon_at"]; // 添加普通控制器,占用位置 [self addChildViewController:[[UIViewController alloc] init]]; // 添加我的空间控制器 [self addChildViewController:[[CZAboutMeViewController alloc] init] title:@"我的空间" imageName:@"tabbar_icon_space"]; // 添加发现控制器 [self addChildViewController:[[CZAboutMeViewController alloc] init] title:@"发现" imageName:@"tabbar_icon_more"];
- 效果如下:
懒加载
加号按钮
@interface
中@interface CZTabBarController () /// 撰写按钮 @property (nonatomic, strong) UIButton *composeButton; @end
@implementation
中#pragma mark - 懒加载 - (UIButton *)composeButton { if (_composeButton == nil) { _composeButton = [[UIButton alloc] init]; [_composeButton setImage:[UIImage imageNamed:@"tabbar_btn"] forState:UIControlStateNormal]; } return _composeButton; }
在
viewDidLoad
中将composeButton
添加到tabBar
, 并设置frame
// 添加加号按钮 [self.tabBar addSubview:self.composeButton]; // 设置加号按钮frame CGFloat width = self.tabBar.frame.size.width / TabBarItemCount; self.composeButton.frame = CGRectMake(2 * width, 0, width, self.tabBar.frame.size.height);
- 发现
加号按钮
图片变形 设置按钮图片的填充模式:
#pragma mark - 懒加载 - (UIButton *)composeButton { if (_composeButton == nil) { _composeButton = [[UIButton alloc] init]; [_composeButton setImage:[UIImage imageNamed:@"tabbar_btn"] forState:UIControlStateNormal]; // 设置按钮图片的填充模式 _composeButton.imageView.contentMode = UIViewContentModeScaleAspectFit; } return _composeButton; }
- 点击
加号按钮
发现响应的还是空白的tabBarItem
,查看视图层次结构 在
viewWillAppear
来设置加号按钮
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self setupComposeButton]; } /// 设置加号按钮 - (void)setupComposeButton { // 添加加号按钮 [self.tabBar addSubview:self.composeButton]; // 设置加号按钮frame CGFloat width = self.tabBar.frame.size.width / TabBarItemCount; self.composeButton.frame = CGRectMake(2 * width, 0, width, self.tabBar.frame.size.height); }
由于每个
tabbarItem
之间有一些间距,点击加号按钮
的边上还是有可能会响应到占位的tabbarItem
, 需要将加号按钮
frame的宽度设置大一点/// 设置加号按钮 - (void)setupComposeButton { // 添加加号按钮 [self.tabBar addSubview:self.composeButton]; // 设置加号按钮frame CGFloat width = self.tabBar.frame.size.width / TabBarItemCount; self.composeButton.frame = CGRectMake(2 * width - 2, 0, width + 4, self.tabBar.frame.size.height); }