2016-10-05 53 views
1

我的屏幕上有一个可以拖放的图像。这已经起作用了。当我把手指放在中间时。 就像我把手指放在任何角落(或其他不是中间的东西)一样,图像的中间位于我的手指下。但我仍然想要拥有这个角落。如何用swift精确拖放图像?

这里是我的代码:

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

你的问题在这里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) 
} 
+0

谢谢!我试过了,但现在这个图像已经不在我的手指之下了。也许我可以修复它... –

+0

@chocolatecake,我编辑了答案。现在''initialLocation'的计算是正确的。当触摸结束或取消时,不要忘记重置它。 –

+0

是的,现在它工作!我只是通过添加包含对象初始位置的辅助'initialLocation'来修复它。我计算了这样的新位置: 'let xPos =((touch?.location(in:self.superview))?. x)! - initialLocationFinger!.x;让yPos =((touch?.location(in:self.superview))?。y)! - initialLocationFinger!.y; self.center = CGPoint(x:initialLocationObject!.x + xPos,y:initialLocationObject!.y + yPos);' 但我认为你的解决方案更聪明;) –