Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yuhua-chen/d63d94e37ba9b5e208ef to your computer and use it in GitHub Desktop.
Save yuhua-chen/d63d94e37ba9b5e208ef to your computer and use it in GitHub Desktop.
Demo the drag and drop UITableViewCell in Swift 2.
struct Drag {
static var placeholderView: UIView!
static var sourceIndexPath: NSIndexPath!
}
func handleLongPress(gesture: UILongPressGestureRecognizer) {
let point = gesture.locationInView(tableView)
let indexPath = tableView.indexPathForRowAtPoint(point)
switch gesture.state {
case .Began:
if let indexPath = indexPath {
let cell = tableView.cellForRowAtIndexPath(indexPath)!
Drag.sourceIndexPath = indexPath
var center = cell.center
Drag.placeholderView = placeholderFromView(cell)
Drag.placeholderView.center = center
Drag.placeholderView.alpha = 0
tableView.addSubview(Drag.placeholderView)
UIView.animateWithDuration(0.25, animations: {
center.y = point.y
Drag.placeholderView.center = center
Drag.placeholderView.transform = CGAffineTransformMakeScale(1.05, 1.05)
Drag.placeholderView.alpha = 0.95
cell.alpha = 0
}, completion: { (_) in
cell.hidden = true
})
}
case .Changed:
guard let indexPath = indexPath else {
return
}
var center = Drag.placeholderView.center
center.y = point.y
Drag.placeholderView.center = center
if indexPath != Drag.sourceIndexPath {
swap(&currentList.orderItems[indexPath.row], &currentList.orderItems[Drag.sourceIndexPath.row])
tableView.moveRowAtIndexPath(Drag.sourceIndexPath, toIndexPath: indexPath)
Drag.sourceIndexPath = indexPath
}
default:
if let cell = tableView.cellForRowAtIndexPath(Drag.sourceIndexPath) {
cell.hidden = false
cell.alpha = 0
UIView.animateWithDuration(0.25, animations: {
Drag.placeholderView.center = cell.center
Drag.placeholderView.transform = CGAffineTransformIdentity
Drag.placeholderView.alpha = 0
cell.alpha = 1
}, completion: { (_) in
Drag.sourceIndexPath = nil
Drag.placeholderView.removeFromSuperview()
Drag.placeholderView = nil
})
}
}
}
func placeholderFromView(view: UIView) -> UIView {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
view.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
let snapshotView : UIView = UIImageView(image: image)
snapshotView.layer.masksToBounds = false
snapshotView.layer.cornerRadius = 0.0
snapshotView.layer.shadowOffset = CGSizeMake(-5.0, 0.0)
snapshotView.layer.shadowRadius = 5.0
snapshotView.layer.shadowOpacity = 0.4
return snapshotView
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment