我有一个自定义的tableview单元格,其中包含一个内容,我想将其保存在新控制器中,当我调用YouTube api时,我将max结果设置为2,并且它仅在tableview中显示2行。当我尝试保存在新控制器中时,它保存了3,其中之一正在复制。我该如何保存?我已经选择了sender.tag,但仍然返回3。
这是我在VideoController中的表格视图中的代码
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "videoId", for: indexPath) as! VideoCell
let video = videos[indexPath.row]
cell.video = video
cell.favoriteButton.tag = indexPath.row
cell.favoriteButton.addTarget(self, action: #selector(handleFavorite(sender:)), for: .touchUpInside)
return cell
}
这是我的 handleFavorite 函数,并在我的VideoController中添加委托
var delegate: SaveFavoriteDelegate?
@objc fileprivate func handleFavorite(sender: UIButton) {
let alert = UIAlertController(title: "Add to Favorite", message: nil, preferredStyle: .alert)
let action = UIAlertAction(title: "Favorite", style: .default) { (_) in
let context = CoreDataManager.shared.persistenceContainer.viewContext
let video = NSEntityDescription.insertNewObject(forEntityName: "Video", into: context)
video.setValue(self.videos[sender.tag].videoTitle, forKey: "videoTitle")
video.setValue(self.videos[sender.tag].videoId, forKey: "videoId")
do {
try context.save()
self.delegate?.didAddVideoFavorite(for: video as! Video)
} catch let saveErr {
print("Failed to save into core data:", saveErr)
}
}
alert.addAction(action)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alert, animated: true)
}
我制定了一个协议来处理将数据传递到新控制器中的操作,这就是我的协议代码
protocol SaveFavoriteDelegate {
func didAddVideoFavorite(for video: Video)
}
extension FavoriteController: SaveFavoriteDelegate {
func didAddVideoFavorite(for video: Video) {
videos.append(video)
let newIndexPath = IndexPath(row: videos.count - 1, section: 0)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
}