UIButton标签显示来自Firebase的子值

时间:2017-05-16 03:20:21

标签: swift firebase firebase-realtime-database uibutton parent-child

我正在尝试实现UIButton标题文本,以显示一个文本字符串,其中包含Firebase数据库中子值的数量。在viewDidLoad上,我希望按钮显示firebase数据库中存在的“place”子值的“#”。请参阅下面的代码和firebase数据模型。提前谢谢!

// JSON data model
{
  "users" : {
    "CmtuebwVrmOG3n4uSsIK1b4FsSN2" : {
      "Places" : {
        "-KhDwZJvca9HedFluJ5O" : {
          "addedBy" : "CmtuebwVrmOG3n4uSsIK1b4FsSN2",
          "place" : "Edinburgh, UK",
          "timestamp" : 1.491678152020824E9
        },
        "-KhE7raDrM2RRs-N6FXg" : {
          "addedBy" : "CmtuebwVrmOG3n4uSsIK1b4FsSN2",
          "place" : "Hong Kong",
          "timestamp" : 1.49168137667081E9
        },
        "-KhFUaEjjhE3RBOw95fc" : {
          "addedBy" : "CmtuebwVrmOG3n4uSsIK1b4FsSN2",
          "place" : "Illinois, USA",
          "timestamp" : 1.491704112134812E9
        },
        "-Kk4EI1D7fuPyY2rvbdW" : {
          "addedBy" : "CmtuebwVrmOG3n4uSsIK1b4FsSN2",
          "place" : "Karnataka, India",
          "timestamp" : 1.494736515236516E9
        }
      },
    },  

    var placesTableView: PlacesTableVC?
    var placeList = [Place]()
    var placesDictionary = [String: Place]()
    var tableViewCount: Int?

    lazy var placesButton: UIButton = {
        let customButton = UIButton()
        customButton.backgroundColor = UIColor.blue
        // display the number of place values from firebase in the button title text
        customButton.setTitle("\(self.placesTableView?.placeList.count ?? 0) Visited Places", for: .normal)
        customButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        customButton.setTitleColor(.white, for: .normal)
        customButton.addTarget(self, action: #selector(handleShowPlacesVC), for: .touchUpInside)

        return customButton
    }()

1 个答案:

答案 0 :(得分:1)

使用snapshot.childrenCount来检索节点的子计数。

let placesRef = self.ref.child("users/CmtuebwVrmOG3n4uSsIK1b4FsSN2/Places")
placesRef.observe(.value, with: { snapshot in
     print(snapshot.childrenCount)
     let count = String(snapshot.childrenCount)
     self.myButton.setTitle(count, for: .normal)
})