在我的应用程序中,我需要显示徽章值取决于购物车项目数量,我已经在视图控制器中实现了以下行,我使用json获取数据,并且每当视图控制器是删除后显示并没有更新值,并且在应用程序启动时没有显示徽章值,因为我是swift 3的新手我不知道在哪里实现它可以帮助我如何清除问题?
let appDelegate = UIApplication.shared.delegate as! AppDelegate
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
// print(jsonObj!.value(forKey: "Detail"))
self.itemsArray = (jsonObj!.value(forKey: "Detail") as? [[String: AnyObject]])!
print(self.itemsArray.count)
OperationQueue.main.addOperation({
self.tableDetails.reloadData()
let key = "productPrice"
for array in self.itemsArray{
if let value = array[key] {
let cart = String(describing: value)
let endIndex = cart.index(cart.endIndex, offsetBy: -2)
let truncated = cart.substring(to: endIndex)
self.totalcartPrice.append(truncated)
print(self.totalcartPrice)
var sum = 0.00
for numbers in self.totalcartPrice{
sum += Double(numbers)!
}
print(sum)
self.increment = Int(sum)
self.total = String(sum) + "0KD"
let tabItems = self.tabBarController?.tabBar.items as NSArray!
let tabItem = tabItems?[1] as! UITabBarItem
self.appDelegate.badgeValue = String(Int(self.itemsArray.count))
}
}
})
}
}).resume()
}
func deleteButtonAction(button : UIButton) {
let buttonPosition = button.convert(CGPoint(), to: tableDetails)
let index = tableDetails.indexPathForRow(at: buttonPosition)
self.itemsArray.remove(at: (index?.row)!)
self.tableDetails.deleteRows(at: [index!], with: .automatic)
tableDetails.reloadData()
let tabItems = self.tabBarController?.tabBar.items as NSArray!
let tabItem = tabItems?[1] as! UITabBarItem
self.appDelegate.badgeValue = String(Int(self.itemsArray.count))
if (tableView(tableDetails, numberOfRowsInSection: 0) == 0){
tableDetails.isHidden = true
emptyView.isHidden = false
}
}
答案 0 :(得分:1)
您需要让rootViewController从AppDelegate更新徽章。喜欢这个
let rootViewController = self.window?.rootViewController as!UITabBarController!
let tabArray = rootViewController?.tabBar.items as NSArray!
let tabItem = tabArray.objectAtIndex(1) as! UITabBarItem
tabItem.badgeValue = "34"