注意:使用UIViewController来自定义UITabBarController,在视图控制器切换的时候,会出现TabBar与界面脱节,也就是切换不协调的情况,会影响用户体验。
自定义UITabBarController的关键点在于自定义一个“容器”,用来存放各个控制器。
1.首先创建各个子视图控制器,我用的故事板创建的,新浪微博项目。
// 创建子控制器
- (void)createViewControllers{
// 定义子控制器模块的名字
NSArray *storyBoardNames = @[@"Home",
@"Message",
@"Profile",
@"Discover",
@"More"
];
for (int i = 0; i < storyBoardNames.count; i++) {
NSString *name = storyBoardNames[i];
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:name bundle:nil];
WeiboNavigationViewController *navigation = [storyBoard instantiateInitialViewController];
[self addChildViewController:navigation];
}
// 取得第一个子视图控制器
UIViewController *firstVC = [self.childViewControllers firstObject];
// 显示第一个子视图控制器
[self.view insertSubview:firstVC.view belowSubview:_tabBarView];
}
如上述代码childViewControllers就是“容器”,现在所有的子视图控制器都已经添加好了,下面来实现控制器之间的切换功能。在详述实现功能前,必须的说清楚,TabBar的五个按钮可以是button也可以是image。都对应了相同的点击事件,用tag值来进行区分。
- (void)clickAction:(UIButton *)button{
NSInteger index = button.tag;
self.selectIndex = index;
[UIView animateWithDuration:0.2 animations:^{
_selectImageView.center = button.center;
}];
}
其中selectIndex是UIViewController的属性,用来区分子视图控制器的索引。当selectIndex的值被改变的时候会调用它的set方法,实现子视图的切换<span style="font-size:18px;">- (void)setSelectIndex:(NSInteger)selectIndex{
if (_selectIndex != selectIndex) {
// 取得之前的子控制器
UIViewController *lastVC = self.childViewControllers[_selectIndex];
// 取得当前的选中的子控制器
UIViewController *currentVC = self.childViewControllers[selectIndex];
// 移除上一个子控制器
[lastVC.view removeFromSuperview];
// 添加当前子控制的视图
[self.view insertSubview:currentVC.view belowSubview:_tabBarView];
_selectIndex = selectIndex;
}
}</span>到这里,应该也差不多了,剩下的就是实践了!
在尝试使用UIViewController自定义UITabBarController时,可能会遇到TabBar与界面同步问题,导致视图切换不协调。解决这个问题的关键在于创建一个容器来容纳各个子控制器。本文以新浪微博项目为例,介绍如何通过故事板创建子视图控制器并实现流畅的TabBar切换效果。
4748

被折叠的 条评论
为什么被折叠?



