我有一个网格电影的 View 。有三个属性:标题标签、海报电影的 ImageView 和显示电影是否受欢迎的图像。
当单击一个单元格时,进入详细 View ,显示其他有关电影的信息,并且有一个按钮操作来支持电影。我希望更新网格 Collection View 中的按钮图标。因此,我创建了一个委托(delegate)以在此事件发生时进行监听,然后重新加载 Collection View 。
截图:
grid movies screen
detail movie screen
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! MoviesCollectionViewCell
cell.titleLabel.text = popularMovies[indexPath.row].title
getImageMovies(imageURLString: popularMovies[indexPath.row].poster, imageView: cell.movieImage)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let detailMovieViewController = DetailMovieViewController()
detailMovieViewController.titleMovieLabel.text = popularMovies[indexPath.row].title
detailMovieViewController.releaseDateMovieLabel.text = popularMovies[indexPath.row].date
detailMovieViewController.overviewMovieLabel.text = popularMovies[indexPath.row].overview
getImageMovies(imageURLString: popularMovies[indexPath.row].poster, imageView: detailMovieViewController.movieImage)
getGenresMovies(genresMoviesID: popularMovies[indexPath.row].genre, genreMovieLabel: detailMovieViewController.genreMovieLabel)
collectionView.deselectItem(at: indexPath, animated: true)
detailMovieViewController.delegate = self
selectedIndexPath = indexPath
self.navigationController?.pushViewController(detailMovieViewController, animated: true)
}
protocol favoriteMovieDelegate: class {
func updateFavoriteImage ()
}
@objc func markFavoriteButtom (buttom: UIButton){
if buttom.isSelected == false {
buttom.isSelected = true
}else {
buttom.isSelected = false
}
delegate?.updateFavoriteImage()
}
func updateFavoriteImage() {
if let indexPath = selectedIndexPath {
let cell = collectionView.cellForItem(at: indexPath) as! MoviesCollectionViewCell
cell.favoriteIconImage.image = UIImage(named: "favorite_full_icon")
collectionView.reloadData()
}
}
struct Films: Codable {
let id: Int
let title: String
let poster: String
let genre: [Int]
let date: String
let overview: String
enum CodingKeys: String, CodingKey {
case id
case title
case poster = "poster_path"
case genre = "genre_ids"
case date = "release_date"
case overview
}
}
最佳答案
而不是直接更新您的cell.favoriteIconImage.image
您必须直接更新您的对象,然后重新加载 CollectionView
.您需要在 cellForItem
上设置收藏图片此外,您需要将其发布到服务器,一旦用户将其设为 fav ... 并获取 isFav
如果要保留数据,请从服务器。如果您的服务器不支持 isFav
那么您需要将其存储在本地,以针对 film Id
...在 user default
关于ios - 使用 uicollectionview Swift 更新单个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63103259/