0

我有一个带有 PHP 和 MySQL 后端的 iPhone 应用程序。我在底部有一个标签栏,想要显示一个徽章,显示存储在数据库中的用户消息的数量。

我已经测试了 PHP 文件和 MySQL 查询,它们都可以工作。我还对徽章编号进行了硬编码,以查看 Swift 代码是否也能正常工作。我被卡住的地方是当我将所有三个放在一起时,值仍然没有显示在 tab bar 上。我打印了值,它确实不在选项卡上。

这是代码:

// 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          
   } 
4

1 回答 1

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)"

    }
}
于 2018-08-11T16:47:29.437 回答