问题描述
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!
}
解决方法
可能最好的地方是在您的 DeleteViewController
中,假设这个类保存您的集合视图并且是它的数据源。
您可以简单地添加一个新属性,例如 headerText: String
,然后它可能是您的数据源方法中的用户。每当您更改文本时,您都应该重新加载集合视图(或仅标题)以使更改生效。
例如
class DeleteViewController: UIViewController,UICollectionViewDataSource {
@IBOutlet private var collectionView: UICollectionView?
private var currentHeaderText: String = "Dummy"
override func viewDidLoad() {
super.viewDidLoad()
changeHeaderText(to: "Some other text")
}
private func changeHeaderText(to text: String) {
currentHeaderText = text
collectionView?.reloadData()
}
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 = currentHeaderText
return headerView
}
}
更优化的方法可能是检测哪些索引路径需要重新加载,并且只重新加载那些索引路径。甚至可以使用 collectionView?.visibleSupplementaryViews(ofKind: <#T##String#>)
之类的方法并遍历与您的类相对应的所有可见视图以应用更改。但这完全取决于您。