我无法与我的CollectionView单元格互动

时间:2019-12-21 16:49:03

标签: ios swift uicollectionview

我正在尝试与CollectionView中的单元进行交互,但是我什么也无法工作。

起初,我只是想通过单击单元格将某些内容打印到日志中。那没用。我通过声明“ didSelectItemAt”函数来做到这一点。

接下来,我在该单元格中添加了一个按钮,并添加了IBAction以将某些内容打印到日志中,但这也不起作用。

我尝试将collectionview.isUserInteractionEnabled = true添加到viewDidLoad()方法中,但这没有用。我还检查了情节提要

我正在通过添加数据源和委托

collectionview.delegate = self
collectionview.dataSource = self

我还尝试在viewDidLoad中添加UITapGestureRecognizer,但这只是使我的应用在加载视图时崩溃。

我可以与其他collectionview进行交互,但是我不能与该collection view进行交互。我不确定滚动是否可行,因为到目前为止该集合视图中仅加载一个单元格。

有人对我能做什么或如何正确实现UITapGestureRecognizer有任何想法吗?

这是CollectionView的完整代码:


import UIKit
import Firebase
import SwiftKeychainWrapper
import SwiftUI
import FirebaseUI


class UserViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {


    @IBOutlet weak var collectionview: UICollectionView!

    var user = [User]()
    var following = [String]()

    var userStorage: StorageReference!
    var ref : DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionview.delegate = self
        collectionview.dataSource = self

        collectionview.isUserInteractionEnabled = true
//        self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UserCell")

        retrieveUsers()
//        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
//        tap.cancelsTouchesInView = false
//        collectionview.addGestureRecognizer(tap)
    }

    @IBAction func buttonPress(_sender: Any){
        print("fuck you")
    }


    func retrieveUsers() {
        let uid = Auth.auth().currentUser!.uid
        let ref = Database.database().reference().child("posts")
        let uids = Database.database().reference().child("users")
        uids.observeSingleEvent(of:.value, with:{
            (snapshot) in
                    let users = snapshot.value as! [String : NSDictionary]
                        //self.user.removeAll()
                        for (_, value) in users {

                            if let uid = value["uid"] as? String {
                                if uid != Auth.auth().currentUser!.uid {
                                    let userToShow = User()
                                    if let username = value["username"] as? String, let imagePath = value["urlToImage"] as? String{

                                        userToShow.username = username
                                        userToShow.imagePath = imagePath
                                        userToShow.userID = uid
                                        self.user.append(userToShow)
                                        print(userToShow)
                                    }
                                }
                            }
                        }
                        self.collectionview.reloadData()
                    })
                    //ref.removeAllObservers()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
           return user.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let cell = collectionview.dequeueReusableCell(withReuseIdentifier: "userCell", for: indexPath) as! UserCell



          cell.userImage.sd_setImage(with: URL(string: self.user[indexPath.row].imagePath))

           cell.nameLabel.text = self.user[indexPath.row].username
           cell.userID = self.user[indexPath.row].userID
//        let destinationVC = ProfileViewController()
//        destinationVC.sentUserID = user[indexPath.row].userID!

        // Let's assume that the segue name is called playerSegue
        // This will perform the segue and pre-load the variable for you to use
        //destinationVC.performSegue(withIdentifier: "toProfileFromSearch", sender: self)


//        cell.addButtonTapAction = {
//            // implement your logic here, e.g. call preformSegue()
//            self.performSegue(withIdentifier: "toProfileFromSearch", sender: self)
//        }
        //cell.userImage.downloadImage(from: self.user[indexPath.row].imagePath!)
        //checkFollowing(indexPath: indexPath)


        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        print("hello world")
//        let VC1 = self.storyboard!.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
//        VC1.sentUserID = user[indexPath.row].userID
//        self.navigationController?.pushViewController(VC1, animated: true)
    }












    func checkFollowing(indexPath: IndexPath) {
        let uid = Auth.auth().currentUser!.uid
        let ref = Database.database().reference()

        ref.child("users").child(uid).child("following").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in

            if let following = snapshot.value as? [String : AnyObject] {
                for (_, value) in following {
                    if value as! String == self.user[indexPath.row].userID {
//                        self.tableview.cellForRow(at: indexPath)?.accessoryType = .checkmark
                    }
                }
            }
        })
        ref.removeAllObservers()

    }

    @IBAction func logOutPressed(_ sender: Any) {
        KeychainWrapper.standard.removeObject(forKey:"uid")

        do{
            try Auth.auth().signOut()
        } catch let signOutError as NSError{
            print("Error signing out: %@", signOutError)
        }
        dismiss(animated: true, completion: nil)
    }

}


extension UIImageView {

    func downloadImage(from imgURL: String!) {
        let url = URLRequest(url: URL(string: imgURL)!)

        let task = URLSession.shared.dataTask(with: url) {
            (data, response, error) in

            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                self.image = UIImage(data: data!)
            }

        }

        task.resume()
    }
}

0 个答案:

没有答案