我过去使用 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。解决这个问题的最佳方法是什么?是否有另一个库允许滑动删除部分(我找不到)?或者这是我必须自己创造的东西。
最佳答案
我还没有对此进行测试,但想法如下。获取 View (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)
})
}
}
关于ios - 滑动以删除 UITableView 中的整个部分(iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46739072/