我正在使用 UISwipeGestureRecognizer 检测 UITableViewCell 中某个单元格的滑动,类似于THIS LINK,这将允许用户'喜欢'一张照片。
问题是我不太了解如何更改特定帖子的 Like 值-而且它不像其他“内置”方法那样具有indexPath。我也不明白如何使用主要显示在屏幕上的单元格,因为可能有多个单元格尚未“出队”?:
@objc func mySwipeAction (swipe: UISwipeGestureRecognizer) {
switch swipe.direction.rawValue {
case 1:
print ("the PostID you selected to LIKE is ...")
case 2:
print ("the PostID you selected to Undo your LIKE is ...")
default:
break
}
}
我的tableView看起来像这样:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postTopContributions", for: indexPath) as! PostTopContributions
let postImage = postImageArray [indexPath.row]
let imageURL = postImage.postImageURL
cell.delegate = self
cell.postSingleImage.loadImageUsingCacheWithUrlString(imageURL)
cell.postSingleLikes.text = "\(postImageArray [indexPath.row].contributionPhotoLikes)"
cell.postSingleImage.isUserInteractionEnabled = true
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.mySwipeAction(swipe:)))
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.mySwipeAction(swipe:)))
leftSwipe.direction = UISwipeGestureRecognizerDirection.left
rightSwipe.direction = UISwipeGestureRecognizerDirection.right
cell.postSingleImage.addGestureRecognizer(leftSwipe)
cell.postSingleImage.addGestureRecognizer(rightSwipe)
let selectedCell = self.postImageArray [indexPath.row]
return cell
}
我不想使用向左滑动的本机TableView行删除方法-在这种特定情况下出于各种UX目的。
答案 0 :(得分:1)
您可以尝试
cell.postSingleImage.addGestureRecognizer(leftSwipe)
cell.postSingleImage.addGestureRecognizer(rightSwipe)
cell.postSingleImage.tag = indexPath.row
不建议在cellForRowAt中添加手势,您可以添加 它们在init中用于程序化单元,在awakeFromNib中用于xib / 原型细胞
@objc func mySwipeAction (swipe: UISwipeGestureRecognizer) {
let index = swipe.view.tag
let selectedCell = self.postImageArray[index]
switch swipe.direction.rawValue {
case 1:
print ("the PostID you selected to LIKE is ...")
// edit dataSource array
case 2:
print ("the PostID you selected to Undo your LIKE is ...")
// edit dataSource array
default:
break
// reload table IndexPath
}
}
答案 1 :(得分:0)
您可以在选择器中将索引路径作为参数传递。然后在yourArray [indexpath.row]
中添加类似内容答案 2 :(得分:0)
您可以设置要将GestureRecognizer添加到单元格本身的indexPath行的单元格图像的标签:
cell.postSingleImage.tag = indexPath.row
cell.postSingleImage.addGestureRecognizer(leftSwipe)
cell.postSingleImage.addGestureRecognizer(rightSwipe)
然后,您可以通过获取触发了滑动手势的视图标签来确定哪个单元格触发了GestureRecognizer:
@objc func mySwipeAction (gesture: UISwipeGestureRecognizer) {
let indexPathRow = gesture.view.tag
let indexPath = IndexPath(row: indexPathRow, section: 0) // assuming this is a 1 column table not a collection view
if let cell = tableView.cellForRow(at: indexPath) as? PostTopContributions {
// ... and then do what you would like with the PostTopContributions cell object
print ("the PostID you selected to LIKE is ... " + cell.id)
}
}
希望这对您有所帮助!