为什么在viewdidload之前加载集合视图标头?

时间:2017-11-16 10:13:17

标签: ios swift3 uicollectionview xcode8

我正在尝试添加一个活动指示器,但我无法成功执行此操作,因为我的集合视图标头在viewdidload之前加载,因此我在活动指示器开始之前显示了一些内容。有人可以帮助我或指出我正确的方向。我在下面发布了我的代码

viewDidLoad中

 override func viewDidLoad() {
        super.viewDidLoad()

           fetchUser()
   profileCollectionView?.register(guestHeaderCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")

   profileCollectionView?.register(photoViewCollectionViewCell.self, forCellWithReuseIdentifier: cellId)

}

   func fetchUser() {
        self.activityIndicator.startAnimating()

        if let uid = selectedUser.uid{

            Database.fetchUserWithUID(uid: uid) { (user) in
                self.selectedUser = user
                self.navigationItem.title = self.selectedUser?.fullName

                self.profileCollectionView?.reloadData()
                self.activityIndicator.stopAnimating()
                self.activityIndicator.isHidden = true
                self.fetchOrderedPosts()
            }
        }
    }

在viewDidLoad

之前调用的集合视图标题
 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
       let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath) as! guestHeaderCollectionViewCell

        header.user = self.selectedUser
        header.delegate = self

        return header
    }

查看控制器

class newGuestPhotoViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, guestProfileHeaderDelegate, HomePostCellDelegate {

    let cellId = "cellId"
    let homePostCellId = "homePostCellId"

    @IBOutlet weak var profileCollectionView: UICollectionView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    var user: userAccount?
    var selectedUser: userAccount!
    var posts = [Post]()    
    let stringID = NSUUID().uuidString   
    var isGridView = true

    func didChangeToGridView() {
        isGridView = true
        profileCollectionView?.reloadData()
    }

    func didChangeToListView() {
        isGridView = false
        profileCollectionView?.reloadData()
    }

    var showDataFlag : Bool = false!

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchUser()
        profileCollectionView?.register(guestHeaderCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")       
        profileCollectionView?.register(photoViewCollectionViewCell.self, forCellWithReuseIdentifier: cellId)       
        profileCollectionView?.register(newsfeedCollectionViewCell.self, forCellWithReuseIdentifier: homePostCellId)
    }  
    func fetchUser() {
        self.activityIndicator.startAnimating()
        if let uid = selectedUser.uid{

            Database.fetchUserWithUID(uid: uid) { (user) in
                self.selectedUser = user
                self.navigationItem.title = self.selectedUser?.fullName
                self.showDataFlag = true;
                self.profileCollectionView?.reloadData()
                self.activityIndicator.stopAnimating()
                self.activityIndicator.isHidden = true
                self.fetchOrderedPosts()
            }
        }
    }

    fileprivate func fetchOrderedPosts() {
        guard let uid = selectedUser?.uid else { return }
        let ref = Database.database().reference().child("post").child(uid)
        ref.queryOrdered(byChild: "dateOfPost").observe(.childAdded, with: { (snapshot) in            
            guard let dictionary = snapshot.value as? [String: Any] else { return }            
            let uid = dictionary["postUserUID"] as? String

            Database.fetchUserWithUID(uid: uid!, completion: { (userSnap) in

            let post = Post(user:userSnap, dictionary: dictionary)           
            self.posts.insert(post, at: 0)
            guard let uid = Auth.auth().currentUser?.uid else {return}
            Database.database().reference().child("likes").child(post.postID!).child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
                print(snapshot)

                if let value = snapshot.value as? Int, value == 1 {
                    post.hasLiked = true
                } else {
                    post.hasLiked = false
                }

              DispatchQueue.main.async(execute: {
            self.profileCollectionView?.reloadData()
                })
            }, withCancel: { (err) in
                print("Failed to fetch like info for post:", err)
            })

            })
        }) { (err) in
            print("Failed to fetch ordered posts:", err)
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if(!showDataFlag){
            return 0
        }
        return posts.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if isGridView {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! photoViewCollectionViewCell
            cell.post = posts[indexPath.item]

            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: homePostCellId, for: indexPath) as! newsfeedCollectionViewCell
            cell.post = posts[indexPath.item]
            cell.delegate = self

            return cell
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
       let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath) as! guestHeaderCollectionViewCell

        header.user = self.selectedUser
        header.delegate = self

        return header
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: view.frame.width, height: 250)
    }

1 个答案:

答案 0 :(得分:1)

正如我在mi评论中所说,你可以添加一个标志,在fetchUser()后你可以设置这个标志为真,你的collectionView将显示你的数据

类似

var showDataFlag : Bool = false

override func viewDidLoad() {
        super.viewDidLoad()

           fetchUser()
   profileCollectionView?.register(guestHeaderCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")

   profileCollectionView?.register(photoViewCollectionViewCell.self, forCellWithReuseIdentifier: cellId)

}

   func fetchUser() {
        self.activityIndicator.startAnimating()

        if let uid = selectedUser.uid{

            Database.fetchUserWithUID(uid: uid) { (user) in
                self.selectedUser = user
                self.navigationItem.title = self.selectedUser?.fullName

                self.showDataFlag = true;
                self.profileCollectionView?.reloadData()
                self.activityIndicator.stopAnimating()
                self.activityIndicator.isHidden = true
                self.fetchOrderedPosts()
            }
        }
    }

//In your Collection View Data Source Implementation

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if(!showDataFlag){
           return 0
        }
           return yourNeededNumberOfSections
    }