我有一个带PHP和MySQL后端的iPhone应用程序。我在底部有一个标签栏,想要显示一个徽章,其中显示了存储在数据库中的用户消息数。
我已经测试了PHP文件和MySQL查询,它们都可以工作。我还对徽章编号进行了硬编码,以查看Swift代码是否也可以正常工作。卡住的地方是当我将这三个全部放在一起时,值仍然不会显示在标签栏上。我打印了该值,并且确实不在选项卡上。
代码如下:
// func of loading posts from server
func loadPosts()->[String] {
// append all posts var's inf to tweets
self.hhmessages = messages as! [AnyObject]
//print(self.hhmessages)
self.incoming = []
// getting images from url paths
for i in 0 ..< self.hhmessages.count {
// path we are getting from $returnArray that assigned to parseJSON > to posts > tweets
let incoming = self.hhmessages[i]["badgecount"]!
print(incoming! as Any)
// Access the elements (NSArray of UITabBarItem) (tabs) of the tab Bar
let tabItems = self.tabBar.items as NSArray?
// In this case we want to modify the badge number of the third tab:
let tabItem = tabItems![3] as! UITabBarItem
let messagevalue = incoming!
print(messagevalue as Any)
// Now set the badge of the third tab
tabItem.badgeValue = messagevalue as? String
}
// reload tableView to show back information
}
答案 0 :(得分:1)
好的,请尝试使用以下结构。
func loadPosts() {
//1. instead of -> self.hhmessages = messages as! [AnyObject]
self.hhmessages = messages as! [[String: Any]] //the hhmessages shoud be of type [[String: Any]] better readabilty
//2. self.incomin = [] -> What is this used for?
//3. we will create new variable to store all the badge counts for future refrence
var badgeCount = 0
//4. loop through the messages and get the badge count (Not sure if badgeCount is the key or unread)
//but I'll go as you have done
for message in hhmessages {
if let count = message["badgecount"] as? Int {
badgeCount += count
}
}
//5. we have the badge count so we will access the tabbar to which we will display the badge icon
if let tabItems = self.tabBar.items {
let thirdTab = tabItems[2] //get the third tab item
//6. set the value of badge
thirdTab.badgeValue = "\(badgeCount)"
}
}