When I am calling a function on CollectionCiewController
with button on CollectionViewHeader
, it makes all variables nil on c.view
. I couldn't find out where the problem is.
@IBAction func loadmore(_ sender: Any) {
CollectionViewController().goNetwork()
}
called 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!
}}}}
You are calling function on new instance of CollectionViewController
thats why getting everything nil... get the current CollectionViewController
through delegate and call goNetwork on that existing CollectionViewController
object
Write a protocol like this
protocol CollectionHeaderViewDelegate {
func didTapButton()
}
Write CollectionReusableView
class with delegate
class CollectionReusableView: UICollectionReusableView {
@IBOutlet weak var loadBtn: UIButton!
var delegate: CollectionHeaderViewDelegate?
@IBAction func loadmore(_ sender: Any) {
delegate?.didTapButton()
}
}
And in your main Controller class which is CollectionViewController
Write this function
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()
}
Write extension of CollectionViewController
and confirm it with protocol
extension CollectionViewController: CollectionHeaderViewDelegate {
func didTapButton() {
goNetwork()
}
}
Now you have goNetwork in your main controller .... it will load contents automatically ...
thanks