ios - 将数据从表 Cell 内的集合 Cell 传递到二次使用协议(protocol)

标签 ios swift uitableview collections protocols

我有两个 viewController。第一个 VC 在 tableCell 内有 collectionCell。第二个 VC 有 collectionCell,我有 swift File 和 Model 有一个类。我需要将数据从第一个 VC (collectionCell) 传递到第二个 VC。

collectionCell 传递数据需要,因为 collectionCell 有图像(来自 swift 文件 - 模型)。我认为需要使用协议(protocol),但我不太明白如何使用协议(protocol)。请帮忙。

我的代码:

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(tableCell 内的 collectionCell):

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
    }
}

模型(swift 文件有一个类):

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)
            }
        }
    }
}

最佳答案

将 ViewController1 作为 TableViewCell1 的 postDelegate 传递

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
}

最终实现

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

一些建议:

var postDelegate: PostDelegate?

将导致强烈持有对正在传递的委托(delegate)的引用。这将导致内存泄漏。为了使其更安全,将委托(delegate)声明为 weak

weak var postDelegate: PostDelegate?

为了削弱你的协议(protocol)

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

关于ios - 将数据从表 Cell 内的集合 Cell 传递到二次使用协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46152360/

相关文章:

ios - Swift iOS - 如何按特定顺序对数组进行排序?

iOS 今日扩展导致程序以退出代码 : 0 结束

ios - 如何在 Tableview 中使用 Collection View 显示内容

ios - 如何快速使用 CoreData 信息对 UITableView 进行排序?

swift - 结合 didSelectRowAt 和 prepareForSegue?

iphone - 了解OpenGLES iOS中的缓冲区

ios - 在半圆上绘制比例尺 Swift/UIView

ios - 使用 NSCoding 将对象解码为 Int 时抛出的错误是 : fatal error: unexpectedly found nil while unwrapping an Optional value

swift - 在 Swift 中从 SubScrollView 中删除 ImageView

ios - 如何检查 Alamofire 因网络连接不良而失败?