Swift使用Notification Center在两个Collection View间传值收不到通知怎么办
问题原因及解决方案
1. 通知接收不到的核心原因排查
- 首先确认第二个收藏列表的ViewController在你点击第一个列表的按钮时,已经完成初始化并调用过
viewDidLoad方法:如果是点击按钮后才跳转打开第二个VC,此时VC还没注册观察者,自然收不到发送的通知。 - 检查第一个Cell的按钮点击事件是否正常触发:确认控制台有没有输出
Button works fine日志,你当前的点击方法名是likeButoon,注意拼写少了一个t(正确应为likeButton),可能是连线时拼写错误导致事件没触发。
2. 现有逻辑的修正
就算通知能正常接收,你当前的代码也不会刷新第二个列表的UI,且只能存储单一收藏值,无法支持多个收藏项,修正代码如下:
首先修正第二个CollectionViewController的逻辑
// second collection view controller // 改为数组存储多个收藏名称,而非单个字符串 var favoriteNames: [String] = [] override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(notificationRecieved), name: .AddToFavorites, object: nil) } // 收到通知后更新数据并刷新列表 @objc func notificationRecieved(notification: Notification){ guard let name = notification.object as? String else { return } // 可选:避免重复添加同一项 if !favoriteNames.contains(name) { favoriteNames.append(name) } // 必须调用刷新方法,才会触发cellForItemAt重新渲染 collectionViewFavorites.reloadData() } // 补充行数返回方法 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return favoriteNames.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionViewFavorites.dequeueReusableCell(withReuseIdentifier: "favoritesCell", for: indexPath) as! CollectionViewCellFavorites // 从数组取对应位置的名称赋值 cell.nameLabel.text = favoriteNames[indexPath.item] return cell } // 可选:移除观察者避免内存问题 deinit { NotificationCenter.default.removeObserver(self, name: .AddToFavorites, object: nil) }
3. 更稳定的替代方案(如果是点击后才打开第二个VC的场景)
通知只适合通信双方都同时在内存中的场景,如果是点击收藏后才跳转显示收藏列表,建议用全局存储替代通知:
// 全局常量,放在你项目的公共文件或者AppDelegate中 struct GlobalData { static var favoriteNames: [String] = [] }
第一个Cell的点击方法修改为:
@IBAction func likeButton(_ sender: Any) { guard let name = self.nameLabel.text else { return } if !GlobalData.favoriteNames.contains(name) { GlobalData.favoriteNames.append(name) } }
第二个VC在viewWillAppear中刷新即可:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.favoriteNames = GlobalData.favoriteNames collectionViewFavorites.reloadData() }
内容的提问来源于stack exchange,提问作者Nergezeev Alik
相关产品推荐
相关产品推荐

