我有一个称为UICollectionViewControllerSwipingController,它创建一个TeamCell并为其提供“波士顿凯尔特人”的teamName

class SwipingController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = .white
        collectionView?.register(TeamCell.self, forCellWithReuseIdentifier: "cellId")

        collectionView?.isPagingEnabled = true
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! TeamCell

        cell.teamName = "Boston Celtics"

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: view.frame.height)
    }
}

但是,当我运行代码时,teamName仍然打印为空字符串。
class TeamCell: UICollectionViewCell {

    var teamName: String =  ""

    override init(frame: CGRect) {
        super.init(frame: frame)

        print(teamName) //this prints nothing
    }
}

最佳答案

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! TeamCell
它初始化单元格,因此最初它是空的。

初始化cell.teamName = "Boston Celtics"后,实际上没有任何作用

您必须更新名称

class TeamCell: UICollectionViewCell {

    var teamName: String =  ""

    override init(frame: CGRect) {
        super.init(frame: frame)

        print(teamName) //this prints nothing
    }

    func updateName(name : String) {
         self.testName = name

    }

}


在collectionview中
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! TeamCell

        cell.updateName(name : "Boston Celtics")

        return cell
 }

10-04 18:46