gpt4 book ai didi

ios - 为什么我的UICollectionViewCell无法从UICollectionViewController获取数据?

转载 作者:行者123 更新时间:2023-12-01 17:28:25 25 4
gpt4 key购买 nike

我有一个称为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
}

关于ios - 为什么我的UICollectionViewCell无法从UICollectionViewController获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59905929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com