我过去使用 MGSwipeTableCell 滑动以关闭单元格取得了很大的成功,但我目前的任务要求以相同的行为滑动整个部分。
我目前在UITableView中有一个滑动手势识别器,当滑动手势被触发时,我计算接收触摸的部分,并删除填充该部分的对象(在核心数据中),然后调用删除动画:
//Delete objects that populate table datasource
for notification in notifications {
notificationObject.deleted = true
}
DataBaseManager.sharedInstance.save()
let array = indexPathsToDelete
let indexSet = NSMutableIndexSet()
array.forEach(indexSet.add)
//Delete section with animation
self.notificationsTableView.deleteSections(indexSet as IndexSet, with: .left)
这有效,但并不理想。理想情况下,我们希望整个部分用手指拖动(当在某个点释放时,它会离开屏幕),类似于MGSwipeTableCell。 解决这个问题的最佳方法是什么? 是否有另一个允许滑动删除部分的库(我找不到任何库)? 或者这是我必须自己创造的东西。
我还没有测试过这个,但想法如下。查看 ( self.header
) 并使用 touchesBegan...
方法来检测用户将手指放在屏幕上。然后,按照touchesMoved...
方法的手指,计算上一个偏移量与下一个偏移量之间的差异。它应该增长 1(或更多),具体取决于用户移动手指的速度。使用此值减去单元格contentView
的origin.x
。
var header: UIView!
var tableView:UITableView!
var offset:CGFloat = 0
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Touches Began. Disable user activity on UITableView
if let touch = touches.first {
// Get the point where the touch started
let point = touch.location(in: self.header)
offset = point.x
}
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
// Get the point where the touch is moving in header
let point = touch.location(in: self.header)
// Calculate the movement of finger
let x:CGFloat = offset - point.x
if x > 0 {
// Move cells by offset
moveCellsBy(x: x)
}
// Set new offset
offset = point.x
}
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// Reset offset when user lifts finter
offset = 0
}
func moveCellsBy(x: CGFloat) {
// Move each visible cell with the offset
for cell in self.tableView.visibleCells {
// Place in animation block for smoothness
UIView.animate(withDuration: 0.05, animations: {
cell.contentView.frame = CGRect(x: cell.contentView.frame.origin.x - x, y: cell.contentView.frame.origin.y, width: cell.contentView.frame.size.width, height: cell.contentView.frame.size.height)
})
}
}
Brandon 的答案是正确的,但是,INSPullToRefresh 库在使用触摸开始和其他触摸委托方法时存在问题。
我所要做的就是实现一个 UIPanGestureRecognizer,并在触发该手势识别器事件时跟踪触摸