从 UICollectionViewCell 访问保存在 UIViewController 中的变量?

Access variable saved in UIViewController from UICollectionViewCell?

我有一个 MainViewController (MainVC.swift) 和一个 CellViewController (CellVC.swift)。 我的 MainViewController 包含一些标签、按钮和一个集合视图。这个Collection View的cell是由CellViewController控制的(我有一个Cell.xib文件)。

在我的 MainViewController 中,我保存了一些我想在我的 CellViewController 中使用的变量(floatRatingViewWidth、floatRatingViewHeight)。

如何从 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

    }

}

在您的单元格中添加您需要的变量:

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

在你的:

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

做:

cell.cellFloatRatingViewWidth = floatRatingViewWidth