chocolate cake
chocolate cake

Reputation: 2489

How to drag and drop images with swift exactly?

I have an image on my screen that you can drag and drop. That works already. When I put my finger in the middle. Just as I put my finger in any corner (or anything else that is not the middle), the middle of the image gets under my finger. But I still want to have the corner.

Here is my code:

let frameDoor = CGRect(x: 100, y: 100, width: 200, height: 400)
var doorView = ObjectView(frame: frameDoor)
doorView.image = UIImage(named: "door")
doorView.contentMode = .scaleAspectFit
doorView.isUserInteractionEnabled = true
self.view.addSubview(doorView)

ObjectView:

import UIKit

class ObjectView: UIImageView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        var touch = touches.first
        self.center = (touch?.location(in: self.superview))!
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Is there any solution for this?

Upvotes: 1

Views: 1731

Answers (1)

Max Pevsner
Max Pevsner

Reputation: 4094

Your problem is here self.center = (touch?.location(in: self.superview))!.

You should calculate the offset from the center in touchesBegan and then add it when moving the image.

I cannot test the code right now, but it should give you an idea of how to do it.

var initialLocation: CGPoint?    
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     var touch = touches.first
     initialLocation = CGPoint(x: (touch?.location(in: self.superview))!.x - self.center.x, y: (touch?.location(in: self.superview))!.y - self.center.y)
}


override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    var touch = touches.first
    self.center = CGPoint(x: (touch?.location(in: self.superview)).x! - initialLocation.x, y: (touch?.location(in: self.superview)).y! - initialLocation.y)
}

Upvotes: 1

Related Questions