[英]how to get number of this variable in swift 3?
嗨,我正在嘗試在Firebase數據庫中獲取numOfVids,以便可以在我的numberOfItemsInSection中返回該數字。 但是它返回0而不是6。我知道它返回0,因為它讀取的是空變量,而不是observeSingleEvent中的變量。
有什么辦法讓我獲取修改后的numOfVids而不是空的numOfVids?
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numOfVids = Int() // 0
let videosRef = FIRDatabase.database().reference().child("users/\(currentUserID)/videos")
videosRef.observeSingleEvent(of: .value, with: { (snapshot) in
//get user value
numOfVids = Int(snapshot.childrenCount)
print(numOfVids) //prints 6
})
return numOfVids //returns 0
}
先感謝您!
嘗試:-
var numOfVids : Int = 0
@IBOutlet weak var my_CollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.my_CollectionView.delegate = self
self.my_CollectionView.dataSource = self
loadData { (check) in
print(check)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Use only when you want to reload your data every time your view is presented.
/*
loadData { (check) in
print(check)
}
*/
}
func loadData(completionBlock : @escaping ((_ success : Bool?) -> Void)){
Database.database().reference().child("your_PATH").observeSingleEvent(of: .value, with: {(Snap ) in
// Once you have retrieved your data
// Update the count on the class local variable -- numOfVids
// Reload your collectionView as ..
self.my_CollectionView.reloadData()
completionBlock(true)
})
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numOfVids
}
嘗試這個:
let videosRef = FIRDatabase.database().reference().child("users/\(currentUserID)/videos")
videosRef.observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
for data in snapshot.children.allObjects as! [DataSnapshot] {
if let data = data.value {
self.numOfVids = self.numOfVids + 1
}
}
print(numOfVids)
})
關於變量numOfVids:
var numOfVids = 0
那應該工作謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.