2016-10-05 94 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);' 但我認爲你的解決方案更聰明;) –