如何在UICollectionView可复用Cell中引用并更新Label?
报错原因
你遇到的「Reference to member 'cellForItem' cannot be resolved without a contextual type」错误,本质是编译器无法识别collectionView的实例上下文:在collectionView(_:cellForItemAt:)方法里的collectionView是方法传入的参数,但在按钮点击的Info方法中,直接写collectionView如果没有对应IBOutlet实例,编译器不知道你要调用哪个集合视图的方法。另外,即使解决上下文问题,你还需要将获取到的UICollectionViewCell强制转换为自定义的MyColectionCell,否则无法访问CellText这类自定义属性。
两种修复方案
方案1:通过Button的父视图直接获取Cell(更可靠)
这种方法不需要依赖indexPath,直接从点击的Button向上遍历父视图找到对应的自定义Cell,避免cell滚出屏幕时cellForItem(at:)返回nil的情况:
@objc func Info(sender: UIButton){ // 向上遍历父视图找到自定义Cell(根据你的Cell层级调整superview的次数) guard let cell = sender.superview?.superview as? MyColectionCell else { return } let row = cell.Info.tag if ButtonBGs[row] == "bt-tower" { cell.CellText.text = "New Text" } }
方案2:修复CollectionView实例引用并强制转类型
如果你坚持用indexPath获取Cell,需要确保调用的是ViewController中正确的CollectionView实例(比如你的IBOutlet变量),同时强制转换为自定义Cell类型:
// 先确保你的ViewController里有正确的IBOutlet引用 @IBOutlet weak var collectionView: UICollectionView! @objc func Info(sender: UIButton){ let indexPath = IndexPath(row: sender.tag, section: 0) // 用self.collectionView明确指定实例,同时强制转换为自定义Cell guard let cell = self.collectionView.cellForItem(at: indexPath) as? MyColectionCell else { return } if ButtonBGs[indexPath.row] == "bt-tower" { cell.CellText.text = "New Text" } }
补充说明
因为你接受滚动时Label文本被重置,当前cellForItemAt方法中cell.CellText.text = " "的逻辑会在cell复用时自动重置文本,完全符合你的需求,不需要额外修改数据源。
内容的提问来源于stack exchange,提问作者Swick
相关产品推荐
相关产品推荐

