【问题标题】:how to get number of this variable in swift 3?如何在 swift 3 中获取此变量的数量?
【发布时间】:2018-01-13 07:57:45
【问题描述】:

您好,我正在尝试在 Firebase db 中获取 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
}

提前谢谢你!

【问题讨论】:

  • 永远不要将异步任务放入应该返回某些内容的方法中。它行不通。寻找另一个解决方案。例如使用数据源模型,加载viewWillAppear中的数据,并在观察方法的完成处理程序中重新加载集合视图。
  • 没错,在 UICollectionViewDataSource 的方法中做这项工作是不好的方法。

标签: swift xcode firebase uicollectionview


【解决方案1】:

试试:-

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

  }

【讨论】:

    【解决方案2】:

    试试这个:

    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
    

    应该可以了,谢谢

    【讨论】:

    • 它正在和我一起工作,我正在使用它并在视图之间传递值......等等
    • 肯定numberOfItemsInSection中工作
    • 我在这里遗漏了什么吗?您的意思是代码不起作用还是无法解决问题?
    • 好的,那么请写一个完整的答案,让我们都受益于你的知识
    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 2017-08-23
    • 1970-01-01
    • 2021-06-22
    相关资源
    最近更新 更多