我在Collection View Cell
里面有一个按钮每当一个人点击这个按钮时,我想注册一个通知,创建变量name
并将其值设置为单元格的属性nameLabel
,之后我想将该通知发送给我的第二个Collection View
并将Collection View
的单元格nameLabel
.text设置为我从第一个Collection View
发送的name
字符串
如果你需要任何额外的代码,请在评论中告诉我
extension Notification.Name {
static let AddToFavorites = Notification.Name("add_to_favorites")
}
// button inside first collection view cell
@IBAction func likeButoon(_ sender: Any) {
print("Button works fine")
let name = self.nameLabel.text // first collection view cell's property nameLabel
NotificationCenter.default.post(name: .AddToFavorites, object: name)
}
// second collection view controller
var string1: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
}
string1 = name
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionViewFavorites.dequeueReusableCell(withReuseIdentifier: "favoritesCell", for: indexPath) as? CollectionViewCellFavorites
cell?.nameLabel.text = string1 // Second collection view cell's property nameLabel
return cell!
}
你需要刷新
string1 = name
collectionView.reloadData()