【发布时间】:2021-03-26 09:58:38
【问题描述】:
this is screenshot(image) of my viewcontroller我正在使用collectionview并在标题中放置标签,在情节提要中创建标题和标签 我想在运行时更改标签文本。
我知道我可以在 collectionview 的 viewForSupplementaryElementOfKind 中做到这一点,但我希望在 viewdidload 方法中做到这一点
我的代码如下
控制器代码
class DeleteViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = .red
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath) as! TestCollectionReusableView
headerView.labelText.text = "dummy" // this line shows dummy
return headerView
}
let testCollectionReusableView = TestCollectionReusableView()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(TestCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerId")
testCollectionReusableView.labelText.text = "Test"
// above line Xcode 12.4 shows error - **Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value**
}
}
头类文件
class TestCollectionReusableView: UICollectionReusableView {
@IBOutlet weak var labelText: UILabel!
}
【问题讨论】:
标签: ios swift uicollectionview uicollectionreusableview