有谁知道单个标签栏项目是否有可能具有多个关系?
我希望能够从单个 UITabbar 图标定向到两个不同的视图控制器,具体取决于登录的用户类型。
例如,如果用户以用户类型"A"登录,我希望选项卡栏图标定向到配置文件视图控制器。如果用户以用户类型"B"登录,我希望相同的图标定向到设置视图控制器。
我尝试将附加视图控制器连接到选项卡栏,它只是在选项卡栏上创建一个额外的图标/选项卡。
您需要从代码中执行此操作,因此请查看setViewControllers
方法。
假设您有 4 个选项卡对应于vc1
vc2
vc A or B
和vc4
...
您可以确定要分配的 VC,然后使用以下命令实例化完整的控制器"集":
// set "vcA" as the 3rd tab
[self.tabBarController setViewControllers:@[vc1, vc2, vcA, vc4] animated:NO];
// or, set "vcB" as the 3rd tab
[self.tabBarController setViewControllers:@[vc1, vc2, vcB, vc4] animated:NO];
或者......节省"手动"实例化控制器的时间......
您可以在情节提要中分配所有 5 个控制器,然后:
// get the array of viewControllers
NSMutableArray *a = self.tabBarController.viewControllers;
// a now contains [vc1, vc2, vcA, vcB, vc4]
// remove "vcA"
[a removeObjectAtIndex:2];
// or, remove "vcB"
[a removeObjectAtIndex:3];
// set the controllers array
[self.tabBarController setViewControllers:a animated:NO];
您还可以在该选项卡的视图控制器中放置一个容器视图,向容器视图添加两个视图,然后根据用户类型在viewDidLoad
期间显示正确的视图。
有时间会添加代码。
这将是一种方法:
A. 跟踪哪种类型的用户登录包含变量、从以前的 viewController 传递或集中保存在数据对象中:
bool userCanAccessProfile = false;
B. 根据上述布尔值,相应地更新布局和逻辑代码:
//layout your tab bar
UITabBar * tabBar = [UITabBar new];
tabBar.frame = CGRectMake(0, h-50, w, 50);
tabBar.delegate = self;
[self.view addSubview:tabBar];
//create the item(s)
UITabBarItem * item = [UITabBarItem new];
item.title = (userCanAccessProfile) ? @"Profile" : @"Settings";
item.image = (userCanAccessProfile) ? [UIImage imageNamed:@"profile.png"] : [UIImage imageNamed:@"settings.png"];
[tabBar setItems:@[item]];
上面看起来像这样的行,意思是这样的:
something = (isThisTrue) ? (true) setThisValue : (false) setAnotherValue;
您询问userCanAccessProfile是否为真,如果是,则相应地设置不同的文本和图像。
三.当用户单击该项目时,您将再次查询布尔值以找出要执行的操作:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
//when the item is clicked
if (userCanAccessProfile){
//open profile
} else {
//open settings
}
}
请务必在 .m 文件中设置委托:
tabBar.delegate = self;
并将委托添加到 .h 文件中:
@interface yourVC : UIViewController <UITabBarDelegate>