CollectionViewController

CollectionViewController

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

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

称为func:
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 CollectionReusableView: UICollectionReusableView {

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

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

  }

}

在您的主Controller类中,它是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 ....它将自动加载内容...

,谢谢

关于ios - 从外部调用函数后,CollectionViewController上的Swift变量重置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61579073/

10-12 07:17