ios - 使用 NotificationCenter 将数据从 CollectionView 发送到 CollectionView 二
问题描述
我有一个单元格,其中包含一些属性,例如pfp
(图像)mainImage
(图像)description
(字符串)和一个单元格中的类似按钮,单击该按钮后,我想注册一个通知并CollectionView two
在该通知中接收该通知我必须有一个整个单元格,类似于 facebook 分享按钮,每当我分享(点赞)帖子时,该帖子会附加到我的个人资料中,我想编写相同的逻辑,但我有一个点赞按钮而不是分享
//CollectionViewCell where like button is located
@IBOutlet weak var profilePictureImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var desc: UILabel!
@IBOutlet weak var logo: UIImageView!
@IBOutlet weak var likeButton: UIButton!
func setup(with myArray: feedPage){
self.nameLabel.text = myArray.pfName
self.desc.text = myArray.description
self.profilePictureImage.image = myArray.pfp
self.logo.image = myArray.pfp
self.mainImage.image = myArray.mainImage
self.likeButton.setImage(UIImage(named: "like"), for: UIControl.State.normal)
}
@IBAction func likeButoon(_ sender: Any) {
NotificationCenter.default.post(name: Notification.Name("AddToFavorites"), object: nil)
var aaa = self.nameLabel.text
}
//CollectionViewController two where I need to recieve a notification and configure second view controller cell
var test:[String] = []
NotificationCenter.default.addObserver(self, selector: #selector(notificationRecieved), name: Notification.Name("AddToFavorites"), object: nil)
}
@objc func notificationRecieved(){
self.test = aaa //error is here xcode can't find `aaa` in scope
}
我尝试使用第一个 CollectionViewCell 的值创建一个变量aaa
,然后将其放入一个数组中,但它似乎不起作用,如果您需要任何类型的附加信息来解决此问题,任何解决方案都将适用,请在评论,我会补充。谢谢你。
解决方案
您缺少处理通知的一些重要部分,请查看文档以更熟悉它的工作原理。
https://developer.apple.com/documentation/foundation/notificationcenter
话虽如此,您可以通过以下方法实现您想要的。
extension Notification.Name {
static let AddToFavorites = Notification.Name("add_to_favorites")
}
class SomeView: UIView {
@IBOutlet weak var nameLabel: UILabel!
@IBAction func likeButoon(_ sender: Any) {
let name = self.nameLabel.text
// The name value must be sent with the posted notifaction, this enables observers to get the value from the received notification object.
NotificationCenter.default.post(name: .AddToFavorites, object: name)
}
}
class SomeController {
init() {
NotificationCenter.default.addObserver(self, selector: #selector(notificationRecieved), name: .AddToFavorites, object: nil)
}
@objc func notificationRecieved(notification: Notification){
// Retrieve the name value from the notification object.
guard let name = notification.object as? String else {
return
}
// Do something with name
}
}
推荐阅读
- delphi - 套接字错误 #103 软件导致连接中止。德尔福10.4
- python - 保存到磁盘后,具有量化模型的汇总管道中断
- azure - ExponentialBackoffRetry 如何与 Azure 函数的 ServiceBus 触发器一起使用?
- php - PHP - 用于生成 json 文件的数组中的 foreach 循环
- python - 在字典中查找相似键的列表
- c# - 在 .net 5 控制台应用程序中利用用户机密
- java - Spring Cloud Gateway 路径被替换导致错误
- jupyter-notebook - Jupyter Extension 按服务器运行的时区偏移所有时间戳
- c - 继续写我在 C 中的 csv 文件中停止的地方
- assembly - 汇编如何存储信件?