我遇到这种情况:
如何从AppDelegate
访问第3个标签栏徽章?
我用过这段代码:
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
UIViewController *vc = [[UIViewController alloc] init];
if ([nonLette isEqualToString:@"0"]) {
for (vc in tabBarController.viewControllers) {
if (vc.tabBarItem.tag == 999) {
vc.tabBarItem.badgeValue = nil;
}
}
但是self.window.rootViewController
会返回“开始查看”,因此无效。
答案 0 :(得分:2)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabController = storyboard.instantiateViewController(withIdentifier: "TabBarViewController") as! TabBarViewController
let tabArray = tabController.tabBar.items as NSArray!
let alertTabItem = tabArray?.object(at: 3) as! UITabBarItem
alertTabItem.badgeValue = "10"
答案 1 :(得分:0)
好的,我已经解决了,但部分是!!!
此方法效果很好。通过调试,我可以看到现在我可以更改所需选项卡上的徽章,但实际上不会更改图形(不显示红色数字)。
有什么建议吗?
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UITabBarController *myTabBarController = [storyboard instantiateViewControllerWithIdentifier:@"tabBarController"];
if ([nonLette isEqualToString:@"0"]) {
for (UIViewController *vc in myTabBarController.viewControllers) {
if (vc.tabBarItem.tag == 999) {
vc.tabBarItem.badgeValue = nil;
}
}
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
} else {
for (UIViewController *vc in myTabBarController.viewControllers) {
if (vc.tabBarItem.tag == 999) {
vc.tabBarItem.badgeValue = nonLette;
}
}
[UIApplication sharedApplication].applicationIconBadgeNumber=[result integerValue];
}
答案 2 :(得分:0)
使用新的XCode 11和Swift 5不再可能。
相反,您想在SceneDelegate.swift中执行此操作,尤其是此功能func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
然后您想要做这样的事情。
self.window = self.window ?? UIWindow()//@JA- If this scene's self.window is nil then set a new UIWindow object to it.
//@Grab the storyboard and ensure that the tab bar controller is reinstantiated with the details below.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "tabBarController") as! UITabBarController
self.window!.rootViewController = tabBarController //Set the rootViewController to our modified version with the StateController instances
self.window!.makeKeyAndVisible()
print("Finished scene setting code")
guard let _ = (scene as? UIWindowScene) else { return }
希望这对在那里使用较新XCode的人有所帮助。此处的关键是appDelegate不再具有访问窗口的权限,而 sceneDelegate 则具有访问权限。 如果您尝试使用appDelegate,则会收到错误消息,窗口不再存在。
确保在情节提要中为tabBarController设置了标识符,以便可以找到它。您可以使用任何名称命名,但只需在此处的withIdentifier
函数代码中引用该名称