如何使用swift完全拖放图像?

时间:2016-10-05 14:51:43

标签: ios swift touch

我的屏幕上有一个可以拖放的图像。这已经有效了。当我把手指放在中间。 正如我将手指放在任何角落(或其他任何不是中间的角落)时,图像的中间位于我的手指之下。但我仍然想要角落。

这是我的代码:

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")
    }
}

有没有解决方案?

1 个答案:

答案 0 :(得分:1)

您的问题在self.center = (touch?.location(in: self.superview))!

您应该计算touchesBegan中心的偏移量,然后在移动图像时添加它。

我现在无法测试代码,但它应该让您了解如何执行此操作。

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)
}