2017-05-16 4 views
1

Firebaseデータベース内の子値の数を含むテキスト文字列を表示するために、UIButtonタイトルテキストを実装しようとしています。 viewDidLoadで、firebaseデータベースに存在する "place"の子値の "#"を表示するボタンが必要です。以下のコードと火災データベースのデータモデルを参照してください。前もって感謝します!Firebaseからの子値のカウントを表示するUIButtonラベル

// 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 
    }() 
+0

あなたの問題は何ですか? – t4nhpt

+0

こんにちは - UIButtonタイトルテキストに、Firebaseデータベース内に存在する子の値「場所」の数を表示する方法を知りたいです。たとえば、提供されているFirebaseのJSONには4つの「場所」の値がありますので、UIButtonのタイトルテキストに「4」を表示します。ありがとう! – user3708224

答えて

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) 
}) 
+0

ありがとう! – user3708224

関連する問題