【发布时间】:2017-08-22 09:15:17
【问题描述】:
我正在使用 UITabBarController 并使用情节提要中的关系 segue 添加选项卡。
如何根据登录的用户角色隐藏特定的标签?
【问题讨论】:
-
你能详细说明这个问题吗?您可能还需要添加到目前为止您尝试过的代码 sn-p...
标签: ios swift uitabbarcontroller uitabbar ios11
我正在使用 UITabBarController 并使用情节提要中的关系 segue 添加选项卡。
如何根据登录的用户角色隐藏特定的标签?
【问题讨论】:
标签: ios swift uitabbarcontroller uitabbar ios11
好问题!
你需要挖掘UITabbarController及其成员(属性+函数)
现在,专注于这些步骤来寻找解决方案:
viewControllers(它是一个 UIViewController 数组),用于存储使用 UITabbar 项关联的 Tabbar Controller 的 UIViewController。viewControllers 属性控制器。这是应用程序启动的示例:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if var tabController = self.window?.rootViewController as? UITabbarController, var viewControllers = tabController.viewControllers {
let isLoggedIn = <get value from your data storage as bool>
if isLoggedIn {
viewControllers.remove(at: firstIndex) // By considering you need to remove view controller at index first. It will automatically remove tab from tabbar also.
tabController.viewControllers = viewControllers
self.window?.rootViewController = tabController
// further operations to make your root controller visible....
}
}
}
【讨论】:
self.window? 是 AppDelegate 的属性。你不需要初始化它。只需从情节提要创建您的标签栏控制器。从情节提要中将主情节提要和根控制器作为标签栏分配给您的项目。此代码自动工作。
如果您想从标签栏控制器中删除标签,请执行以下操作(当您的用户未登录时)
NSInteger indexToRemove = 0;
NSMutableArray *tabs = [NSMutableArray arrayWithArray:self.tabBarController.viewControllers];
[tabs removeObjectAtIndex:indexToRemove];
self.tabBarController.viewControllers = tabs;
当您的用户登录时
UIViewController *viewController = [[UIViewController alloc] init];
NSMutableArray *tabs = [NSMutableArray arrayWithArray:self.tabBarController.viewControllers];
[tabs addObject:viewController];
self.tabBarController.viewControllers = tabs;
斯威夫特版
删除标签
let indexToRemove = 0
if var tabs = self.tabBarController?.viewControllers {
tabs.remove(at: indexToRemove)
self.tabBarController?.viewControllers = tabs
} else {
print("There is something wrong with tabbar controller")
}
添加标签
let indexToAdd = 2
let vc = UIViewController.init()
if var tabs = self.tabBarController?.viewControllers {
tabs.append(vc) // Append at last index of array
// tabs.insert(vc, at: indexToAdd) // Insert at specific index
self.tabBarController?.viewControllers = tabs
} else {
print("There is something wrong with tabbar controller")
}
【讨论】:
(self.tabBarController?.viewControllers)!。尝试if-let以防止应用崩溃。