从UICollectionViewCell设置collectionView.isHidden=true未生效问题咨询
问题核心原因
你每次调用ThirdViewControllerPassenger()都是在创建一个全新的该视图控制器实例,和当前屏幕上正在显示的、持有你点击的这个cell的ThirdViewControllerPassenger不是同一个对象。新创建的实例没有被添加到视图层级中,它的collectionView甚至可能还没有完成初始化加载,你修改这个全新实例的属性自然不会对当前页面产生任何效果,对应的判断逻辑也不会成立,所以不会打印"done!"。
正确实现方案
有两种常用的实现方式可以解决这个问题:
方式1:闭包回调
- 在你的UICollectionViewCell子类中定义点击回调闭包:
var onCardTapped: (() -> Void)?
- 在cell的onTap方法中触发回调:
@objc func onTap(_ gesture: UIGestureRecognizer) { guard gesture.state == .ended else { return } if favCoordinate.latitude == 1.0 && favCoordinate.longitude == 1.0 { // 待实现逻辑 } else { onCardTapped?() } }
- 在ThirdViewControllerPassenger的
cellForItemAt方法中给cell的闭包赋值:
cell.onCardTapped = { [weak self] in self?.collectionView.isHidden = true if self?.collectionView.isHidden == true { print("done!") } }
方式2:代理模式
- 定义Cell的代理协议:
protocol CardCellDelegate: AnyObject { func cardDidSelect() }
- 在Cell中添加代理属性:
weak var delegate: CardCellDelegate?
- 在onTap的else分支中调用代理方法:
delegate?.cardDidSelect()
- 让ThirdViewControllerPassenger遵守
CardCellDelegate协议,在cellForItemAt中设置cell.delegate = self,然后实现代理方法修改collectionView的隐藏状态即可。
补充说明
你之前描述的"在ThirdViewControllerPassenger内部调用ThirdViewControllerPassenger().collectionView.isHidden = true可以生效"属于描述误差,这种写法同样是创建新实例,不可能生效。你实际生效的写法应该是直接调用当前实例的属性self.collectionView.isHidden = true。
内容的提问来源于stack exchange,提问作者Jan L
相关产品推荐
相关产品推荐

