Kinuhatek
Kinuhatek

Reputation: 85

Access variable saved in UIViewController from UICollectionViewCell?

I have a MainViewController (MainVC.swift) and a CellViewController (CellVC.swift). My MainViewController contains some labels, buttons, and a Collection View. The cell of this Collection View is controlled by CellViewController (I have a Cell.xib file).

In my MainViewController, I have saved some variables (floatRatingViewWidth, floatRatingViewHeight) I want to use in my CellViewController.

How can I access these variables from CellViewController?

MainViewController

class MainVC: UIViewController {
    @IBOutlet weak var collectionView: UICollectionView!

    var floatRatingViewWidth = CGFloat()
    var floatRatingViewHeight = CGFloat()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        collectionView.register(UINib(nibName: "Cell", bundle: nil), forCellWithReuseIdentifier: "myCell")
        collectionView.delegate = self
        collectionView.dataSource = self
 
        settingUpNavBar()
        
        let cellHeight = view.frame.size.height * 0.3
        let cellWidth = view.frame.size.width * 0.42
        
        floatRatingViewWidth = cellWidth - 69
        floatRatingViewHeight = cellHeight * 0.05

    }

}

CellViewController

class CellVC: UICollectionViewCell {

    @IBOutlet weak var ratingHeight: NSLayoutConstraint!
    @IBOutlet weak var ratingWidth: NSLayoutConstraint!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

    }

}

Upvotes: 0

Views: 75

Answers (1)

Claudio Castro
Claudio Castro

Reputation: 1569

In your cell add the vars that you need:

class CellVC: UICollectionViewCell {
    var cellFloatRatingViewWidth : CGFloat?
    var cellFloatRatingViewHeight = CGFloat?

In your:

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

do:

cell.cellFloatRatingViewWidth = floatRatingViewWidth 

Upvotes: 1

Related Questions