简体   繁体   中英

Pass data from collectionCell inside tableCell to secondVC use protocol

I have two viewController's. The first VC has collectionCell inside tableCell . The second VC has collectionCell , and I have swift File with Model have a class. I need to pass data from the first VC ( collectionCell ) to the second VC.

Pass data need from collectionCell because collectionCell has images (from swift File - Model). I think need use a protocol, but I don't really understand how to work with a protocol. Please help.

My code:

1stVC ( viewController ):

class ViewController1: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var image: [Model] = []
    var ref: FIRDatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()

        ref = FIRDatabase.database().reference(withPath: "Студии2")

        ref.observe(.value, with: { (snapshot) in
            var newImages: [Model] = []

            for item in snapshot.children {
                let object = Model(snapshot: item as! FIRDataSnapshot)
                newImages.append(object)
            }
            self.image = newImages
            self.tableView.reloadData()
        })
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
extension ViewController1: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return image.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1
        cell.images = [image[indexPath.row].image,
                       image[indexPath.row].image2]
        return cell
    }
}

1stVC ( collectionCell inside tableCell ):

protocol PostDelegate {
    func selectedPost(cell: String)
}

class TableViewCell1: UITableViewCell {

    var images = [String]()
    var selecetdItem: Model?
    var postDelegate: PostDelegate?

}
extension TableViewCell1: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return images.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell1

        cell.imagesView.sd_setImage(with: URL(string: images[indexPath.item]))

        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        postDelegate?.selectedPost(cell: self.images[indexPath.item])
        print(images[indexPath.item])
    }
}

2ndVC ( viewController ):

class ViewController3: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

//    var images = [String]()
    var images: [Model] = []

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
extension ViewController3: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell3
//        let array = [images[indexPath.item].images,
//                     images[indexPath.item].images2]
//        cell.imagesView.sd_setImage(with: URL(string: array[indexPath.item]))
//        cell.imagesView.sd_setImage(with: URL(string: images[indexPath.item]))
        return cell
    }
}

Model ( swift File have a class ):

class Model {
    var image: String!
    var image2: String!
    var images: [String] = []
    var images2: [String] = []
    var ref: FIRDatabaseReference!

    init(snapshot: FIRDataSnapshot) {
        ref = snapshot.ref
        let value = snapshot.value as! NSDictionary
        let snap1 = value["hall1"] as? NSDictionary
        let snap2 = value["hall2"] as? NSDictionary
        image = snap1?["qwerty"] as? String ?? ""
        image2 = snap2?["qwerty"] as? String ?? ""
        if let post1 = snap1 as? [String: AnyObject] {
            for (_, value) in post1["images"] as! [String: AnyObject] {
                self.images.append(value as! String)
            }
        }
        if let post1 = snap1 as? [String: AnyObject] {
            for (_, value) in post1["images"] as! [String: AnyObject] {
                self.images2.append(value as! String)
            }
        }
    }
}

Pass ViewController1 as the postDelegate of TableViewCell1

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1
      //make VC1 as post delegate of cell
      (cell as! TableViewCell1).postDelegate = self
      cell.images = [image[indexPath.row].image,
                           image[indexPath.row].image2]
      return cell
}

Finally implement

extension ViewController1 : PostDelegate {
    func selectedPost(cell: String) {
         //call self.perform segue or load VC2 and pass data here
    }
}

Pinch of Advice :

var postDelegate: PostDelegate?

will result in strongly holding a reference to the delegate being passed. Which will result in memory leaks. To make it safer declare delegate as weak

weak var postDelegate: PostDelegate?

In order to make the Protocol weak your protocol

protocol PostDelegate: NSObjectProtocol {
    func selectedPost(cell: String)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM