【发布时间】:2017-03-23 22:58:19
【问题描述】:
我有一个包含Album 对象的集合视图。通过点击单元格内的按钮,可以收藏或取消收藏Album。按钮图像会根据 Album 是否被收藏而改变。这部分很简单并且有效。
我遇到的问题是:
- 如果您选择一个单元格,则会出现一个新的视图控制器,该单元格中包含
Album对象。在此视图控制器中,您可以收藏或取消收藏Album对象。 现在,当我关闭此视图控制器时,单元格中的按钮“未”根据Album的isFavorite属性更新。
我认为解决方案是在 UICollectionViewCell 中使用 Realm's Object-Level Notifications。因此,当您在不同的视图控制器中收藏/取消收藏 Album 时,当您返回收藏视图时,按钮是最新的。但我不知道如何添加和删除通知 - 例如在哪里添加/删除以及根据通知在哪里更新?
注意:请不要说使用collectionView.reloadData()。
这是我目前所拥有的(注意评论:var notificationToken: NotificationToken? // Is this where I add the notification for Realm?):
class Album: Object {
dynamic var title = ""
dynamic var isFavorite = false
convenience init(json: [String: Any]) throws {
self.init()
guard let title = json["title"] as? String else {
throw SerializationError.invalidJSON("Album")
}
self.title = title
}
}
protocol AlbumCollectionViewCellDelegate: class {
func didTapFavoriteButton(_ favoriteButton: UIButton, album: Album)
}
class AlbumCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var favoriteButton: UIButton!
weak var delegate: AlbumCollectionViewCellDelegate?
var album: Album!
// HELP
var notificationToken: NotificationToken? // Is this where I add the notification for Realm?
@IBAction func didTapFavoriteButton(_ sender: UIButton) {
delegate?.didTapFavoriteButton(sender, album: album)
}
func configure(with album: Album) {
titleLabel.text = album.title
favoriteButton.isSelected = album.isFavorite
self.album = album
}
}
class FavoritesListViewController: UIViewController, AlbumCollectionViewCellDelegate {
// MARK: - AlbumCollectionViewCellDelegate
func didTapFavoriteButton(_ favoriteButton: UIButton, album: Album) {
favoriteButton.isSelected = album.isFavorite
}
}
有什么想法吗?
【问题讨论】:
标签: ios swift notifications realm