ios - 如何将 View Controller 中的数据传递到另一个 View Controller 中的 Collection View ?

标签 ios iphone swift xcode uicollectionviewcell

<分区>

我正在尝试在 UITextField 中传递数据,用户将输入该数据以进入另一个 View Controller 的 Collection View 中的单元格。

我想创建新的“帖子”,以便在每次有人按下“上传”按钮时添加到我的提要中,因此 Collection View 单元格需要以某种方式上传给定的信息,然后清除单元格。

我不知道如何将数据传递到 Collection View 。

这是我的 View Controller 和我的 Cell 代码。

import UIKit
import Firebase

class UploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {


    @IBOutlet weak var previewImage: UIImageView!
    @IBOutlet weak var postBtn: UIButton!
    @IBOutlet weak var selectBtn: UIButton!

    @IBOutlet weak var thisTextField: UITextField!


    @IBOutlet weak var thatTextField: UITextField!
    var picker = UIImagePickerController()



    @IBAction func thisPhotoUpload(_ sender: Any) {

        if thisTextField.text != "" || thatTextField.text != ""
        {
            performSegue(withIdentifier: "segue", sender: self)
        }

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        var postCell = segue.destination as! PostCell

        postCell.thisString = thisTextField.text!

        postCell.thatString = thatTextField.text!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        picker.delegate = self
    }


    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
            self.previewImage.image = image
            selectBtn.isHidden = true
            postBtn.isHidden = false
        }

        self.dismiss(animated: true, completion: nil)
    }


    @IBAction func selectPressed(_ sender: Any) {

        picker.allowsEditing = true
        picker.sourceType = .photoLibrary

        self.present(picker, animated: true, completion: nil)

    }


    @IBAction func postPressed(_ sender: Any) {
        AppDelegate.instance().showActivityIndicator()

        let uid = FIRAuth.auth()!.currentUser!.uid
        let ref = FIRDatabase.database().reference()
        let storage = FIRStorage.storage().reference(forURL: "gs://instagram-f3f20.appspot.com")

        let key = ref.child("posts").childByAutoId().key
        let imageRef = storage.child("posts").child(uid).child("\(key).jpg")

        let data = UIImageJPEGRepresentation(self.previewImage.image!, 0.6)

        let uploadTask = imageRef.put(data!, metadata: nil) { (metadata, error) in
            if error != nil {
                print(error!.localizedDescription)
                AppDelegate.instance().dismissActivityIndicatos()
                return
            }

            imageRef.downloadURL(completion: { (url, error) in
                if let url = url {
                    let feed = ["userID" : uid,
                                "pathToImage" : url.absoluteString,
                                "likes" : 0,
                                "author" : FIRAuth.auth()!.currentUser!.displayName!,
                                "postID" : key] as [String : Any]

                    let postFeed = ["\(key)" : feed]

                    ref.child("posts").updateChildValues(postFeed)
                    AppDelegate.instance().dismissActivityIndicatos()

                    self.dismiss(animated: true, completion: nil)
                }
            })

        }

        uploadTask.resume()

    }

}

CollectionViewCell 子类

import UIKit
import Firebase

class PostCell: UICollectionViewCell {

    @IBOutlet weak var postImage: UIImageView!
    @IBOutlet weak var authorLabel: UILabel!
    @IBOutlet weak var likeLabel: UILabel!


    @IBOutlet weak var likeBtn: UIButton!
    @IBOutlet weak var unlikeBtn: UIButton!


    @IBOutlet weak var thisLabel: UILabel!
    @IBOutlet weak var thisButton: UIButton!
    @IBOutlet weak var thatLabel: UILabel!
    @IBOutlet weak var thatButton: UIButton!

    var postID: String!
    var thisString = String()
    var thatString = String()



    override func awakeFromNib() {
        super.awakeFromNib()




        thisLabel.text = thisString

        thisButton.setTitle(thisString, for: UIControlState.normal)

        thatLabel.text = thisString

        thatButton.setTitle(thisString, for: UIControlState.normal)
    }

    @IBAction func likePressed(_ sender: Any) {
        self.likeBtn.isEnabled = false
        let ref = FIRDatabase.database().reference()
        let keyToPost = ref.child("posts").childByAutoId().key

        ref.child("posts").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

            if let post = snapshot.value as? [String : AnyObject] {
                let updateLikes: [String : Any] = ["peopleWhoLike/\(keyToPost)" : FIRAuth.auth()!.currentUser!.uid]
                ref.child("posts").child(self.postID).updateChildValues(updateLikes, withCompletionBlock: { (error, reff) in

                    if error == nil {
                        ref.child("posts").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in
                            if let properties = snap.value as? [String : AnyObject] {
                                if let likes = properties["peopleWhoLike"] as? [String : AnyObject] {
                                    let count = likes.count
                                    self.likeLabel.text = "\(count) Likes"

                                    let update = ["likes" : count]
                                    ref.child("posts").child(self.postID).updateChildValues(update)

                                    self.likeBtn.isHidden = true
                                    self.unlikeBtn.isHidden = false
                                    self.likeBtn.isEnabled = true
                                }
                            }
                        })
                    }
                })
            }


        })

        ref.removeAllObservers()
    }


    @IBAction func unlikePressed(_ sender: Any) {
        self.unlikeBtn.isEnabled = false
        let ref = FIRDatabase.database().reference()


        ref.child("posts").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

            if let properties = snapshot.value as? [String : AnyObject] {
                if let peopleWhoLike = properties["peopleWhoLike"] as? [String : AnyObject] {
                    for (id,person) in peopleWhoLike {
                        if person as? String == FIRAuth.auth()!.currentUser!.uid {
                            ref.child("posts").child(self.postID).child("peopleWhoLike").child(id).removeValue(completionBlock: { (error, reff) in
                                if error == nil {
                                    ref.child("posts").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in
                                        if let prop = snap.value as? [String : AnyObject] {
                                            if let likes = prop["peopleWhoLike"] as? [String : AnyObject] {
                                                let count = likes.count
                                                self.likeLabel.text = "\(count) Likes"
                                                ref.child("posts").child(self.postID).updateChildValues(["likes" : count])
                                            }else {
                                                self.likeLabel.text = "0 Likes"
                                                ref.child("posts").child(self.postID).updateChildValues(["likes" : 0])
                                            }
                                        }
                                    })
                                }
                            })

                            self.likeBtn.isHidden = false
                            self.unlikeBtn.isHidden = true
                            self.unlikeBtn.isEnabled = true
                            break

                        }
                    }
                }
            }

        })
        ref.removeAllObservers()
    }
}

现在我在我的 View Controller 中收到错误消息 'var postCell = segue.destination as! PostCell' 行。错误显示“错误执行”

任何和所有的帮助都会很棒。

最佳答案

Segue.destination 返回一个 UIViewController 而不是 UICollectionViewCell

您应该在下一个 View Controller 中创建一个变量并将文本分配给它,然后在那里显示它。

let vc = segue.destination as! NextViewController
vc.thisText = thisTextField.text!
vc.thatText = thatTextField.text!

然后在 NextViewController 中,您将在 thisText 和 thatText 中输入

关于ios - 如何将 View Controller 中的数据传递到另一个 View Controller 中的 Collection View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45633931/

相关文章:

ios - 使用 Firebase 和 GeoFire 通过 Radius 检索位置数据

iphone - 如何在 iOS 中将图像加载到 UITableView 中?

iphone - 原型(prototype)单元不同于动态创建的单元

ios - Pod install 不会安装 pod

ios - 如何在 asnetworkimagenode url 请求中添加身份验证 header ?

ios - UILabel 只模糊文本

ios - UICollectionView 中的 UIImageView 绘制不正确

ios - UIActivityViewController 中的复制链接按钮

Swift XMLParser 无法解析整个字符串

swift - 消息库