Drag & Drop from TableView to Another View in Swift
Currently I does't have the time to test the code, but it should be enough to make sense.... You can do something like this:
class ViewController: UIViewController, UITableViewDataSource {
private var dragView: UIView?
@IBOutlet weak var dropZone: UIView!
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let lpGestureRecognizer: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressCell))
cell.contentView.addGestureRecognizer(lpGestureRecognizer)
return cell
}
func didLongPressCell (recognizer: UILongPressGestureRecognizer) {
switch recognizer.state {
case .Began:
if let cellView: UIView = recognizer.view {
cellView.frame.origin = CGPointZero
dragView = cellView
view.addSubview(dragView!)
}
case .Changed:
dragView?.center = recognizer.locationInView(view)
case .Ended:
if (dragView == nil) {return}
if (CGRectIntersectsRect(dragView!.frame, dropZone.frame)) {
if let cellView: UIView = (dragView?.subviews[0])! as UIView {
cellView.frame.origin = CGPointZero
dropZone.addSubview(cellView)
}
dragView?.removeFromSuperview()
dragView = nil
//Delete row from UITableView if needed...
} else {
//DragView was not dropped in dropszone... Rewind animation...
}
default:
print("Any other action?")
}
}
}
Update on comment:
sure, one possibility would be to tag the fields... like this:
private let imageViewTag: Int = 997
private let textLabelTag: Int = 998
private let detailTtextLabelTag: Int = 999
//...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//...
cell.imageView?.tag = imageViewTag
cell.textLabel?.tag = textLabelTag
cell.detailTextLabel?.tag = detailTtextLabelTag
//...
}
func didLongPressCell (recognizer: UILongPressGestureRecognizer) {
//...
case .Ended:
let cellImageView: UIImageView? = recognizer.view?.viewWithTag(imageViewTag) as? UIImageView
let cellTextLabel: UITextField? = recognizer.view?.viewWithTag(textLabelTag) as? UITextField
let cellDetailTextLabel: UITextField? = recognizer.view?.viewWithTag(detailTtextLabelTag) as? UITextField
//...
}