I have to implement Swipe to remove tableview cell from tableview like Google Now cards. I tried to that logic through touch events. But didnt get that like Google Now. And it is not so smooth. FYI, I have put the following code in my custom tableviewcell
func getGestureDirectionWithTouch(touch:UITouch) -> SwipeDirection{
let gestureEndPoint = touch.location(in: self)
let dx = fabs((self.gestureStartPoint?.x)! - gestureEndPoint.x);
let dy = -1 * (gestureEndPoint.y - (self.gestureStartPoint?.y)!);
if(dx > 20) {
// left/right
return .Right
}
if(dy < 0) {
// down
return .Down
}else if(dy > 0) {
// up
return .Up;
}
return .none
}
// MARK: - Touch Events
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print(#function)
super.touchesBegan(touches, with: event)
if let touch = touches.first {
self.gestureStartPoint = touch.location(in: self)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
print(#function)
if let touch = touches.first {
//gets gesture direction
self.gestureDirection = self.getGestureDirectionWithTouch(touch: touch)
//send event
if (self.gestureDirection == .Left || self.gestureDirection == .Right) {
//exit if view is self or if view can't swipe
// if self.gestureView == self || !self.canSwipe(view: gestureView!) {
// return;
//}
//swipe card
let gestureEndPoint = touch.location(in: self)
self.frame = (self.frame).offsetBy(dx: (gestureEndPoint.x - (self.gestureStartPoint?.x)!),
dy: (0))
if ((self.alpha) > CGFloat(0.4)) {
self.alpha=(self.alpha)-0.01
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print(#function)
//we are swiping a card
let x = self.frame.origin.x
if fabs(Double(x)) > Double(self.frame.size.width/2){
//card will be deleted when x is greater than half width view
}else{
//card will be positioned at the orginila position
self.center = self.cellCenter!
self.alpha=1.0;
}
}
Here touch end event triggered more oftenly. I think thats why the smoothness is not there. Please provide me the best way to achieve the swipe to remove tableviewcell from tableview as like Google Now Cards.
Thanks in advance.