Swift 从外部调用函数后 Collectionviewcontroller 上的变量重置

Swift variables on Collectionviewcontroller resetting after calling a function from outside

当我使用 CollectionViewHeader 上的按钮调用 CollectionCiewController 上的函数时,它使 c.view 上的所有变量都为零。我找不到问题出在哪里。

 @IBAction func loadmore(_ sender: Any) {
        CollectionViewController().goNetwork()  
    }

调用函数:

import UIKit

class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
 var query: QueryForUnogs!
 var dataSource = [REsult]() {
        didSet {
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
    }
override func viewDidLoad() {
        super.viewDidLoad()
        self.goNetwork()
}

func goNetwork() {
        var urlWithParams: String = "https://unogsng.p.rapidapi.com/search?start_year=\(query.minYear!)&end_year=\(query.maxYear!)&start_rating=\(query.minImdb!)&offset=\(self.offset.description)&type=\(query.type!)&end_rating=10&countrylist=\(query.cc!)&orderby=\(query.orderby!)&audio=\(query.audio!)&subtitle=\(query.subtitle!)"

    NetworkService().downloadUnogs(_qu: urlWithParams) { result in
        switch result {
        case .failure(let error): print(error)
        case .success(let RR):
        self.dataSource = RR.results!
}}}}

您正在 CollectionViewController 的新实例上调用函数,这就是为什么将所有内容都设为零...通过委托获取当前 CollectionViewController 并在现有 CollectionViewController 对象上调用 goNetwork

像这样写一个协议

protocol CollectionHeaderViewDelegate {
  func didTapButton()
}

CollectionReusableView class 委托

class CollectionReusableView: UICollectionReusableView {

  @IBOutlet weak var loadBtn: UIButton!
  var delegate: CollectionHeaderViewDelegate?

  @IBAction func loadmore(_ sender: Any) {
    delegate?.didTapButton()

  }

}

并且在您的主控制器中 class 即 CollectionViewController 写这个函数

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    if (kind == UICollectionView.elementKindSectionFooter) {
      let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "LoadFooter", for: indexPath) as! CollectionReusableView
      footerView.delegate = self
      return footerView

    }
    fatalError()

  }

写入 CollectionViewController 的扩展名并用协议确认

extension CollectionViewController: CollectionHeaderViewDelegate {
  func didTapButton() {
     goNetwork()
  }


}

现在你的主控制器中有 goNetwork ....它将自动加载内容......

谢谢