我想从appDelegate更改我的标签栏的图标。
我将解释为什么要这么做。
我从我的网站通过推送将数据发送到我的应用程序,因此在appdelegate中,我通过didReceiveRemoteNotification函数接收了数据,利用这些数据,我手动创建了本地通知。我还希望能够修改我的TabBar的图标,以显示有新的通知。
那么如何从应用程序委托中更改标签栏的图标?
这是我的应用的照片,绿色圆圈表示“新通知”
这是我在appdelegate中的代码:
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable: Any]) {
if let data = data as? NSDictionary {
print("Title: \(data)")
LocalNotification.createLocalNotificationWithIntervals(identifier: "Push",
title: data["title"] as! String,
body: data["body"] as! String,
intervals: 1) { error in
guard error == nil else {
print("Error: \(error!.localizedDescription)")
return
}
print("Successfully execute notification")
}
}
}
我使用了Tabor控制器:
class FittoTabBarController: UITabBarController {
let kImageNoLabelInset: CGFloat = 6.0
var selectedTab: FittoTabBar.Tabs = .pods {
didSet {
selectedIndex = selectedTab.rawValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
selectedTab = .pods
removeItemsTitles()
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
guard let selectedItemIndex = tabBar.items?.index(of: item),
let selectedTab = FittoTabBar.Tabs(rawValue: selectedItemIndex) else {
return
}
self.selectedTab = selectedTab
}
private func removeItemsTitles() {
if let items = self.tabBar.items {
for item in items {
item.title = ""
item.imageInsets = UIEdgeInsets(top: kImageNoLabelInset, left: 0.0, bottom: -kImageNoLabelInset, right: 0.0)
}
}
}
我的应用程序的输入在选项卡控制器上
答案 0 :(得分:0)
使用上面提供的代码,您需要按照以下步骤操作。
在您的FittoTabBarController
中添加这些方法。
func setBadge(_ value: String?) {
_ = self.viewControllers![2].tabBarItem.badgeValue = value
}
func getBadge() -> String? {
return self.viewControllers![2].tabBarItem.badgeValue
}
func resetBadge() {
self.viewControllers![2].tabBarItem.badgeValue = nil
}
在您的appDelegate中,在收到通知时获取窗口的rootViewController
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable: Any]) {
if let data = data as? NSDictionary {
print("Title: \(data)")
let myTabBarController = self.window?.rootViewController as! FittoTabBarController
var newBadgeCount = "1"
if let currentBadgeCount = myTabBarController.getBadge() {
// Convert to int
var intValOfCurrentBadge = Int(currentBadgeCount)!
// Increaset it by one.
intValOfCurrentBadge = intValOfCurrentBadge + 1
// Convert back to string.
newBadgeCount = "\(intValOfCurrentBadge)"
}
// Set your badge value here.
myTabBarController.setBadge(newBadgeCount)
// ADD YOUR EXISTING CODE HERE
}
}
当用户单击第三个选项卡时,只需调用resetBadge()方法即可删除徽章计数。
希望有帮助。