2016-10-05 13 views
1

私はドラッグアンドドロップできる画面上の画像を持っています。それはすでに動作します。真ん中に指を置いたとき。 ちょうど私の指をどこのコーナー(または中央でないもの)に置いても、イメージの真ん中が指の下になります。しかし、私はまだコーナーを持っていたい。ここでイメージをドラッグ&ドロップする方法は?

は私のコードです:

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

はい、今は動作します!私はオブジェクトの初期位置を含む2番目の 'initialLocation'を追加することで修正しました。そして、私は次のように新しい位置を計算しました: 'let xPos =((touch?.location(in:self.superview))?. x)! - initialLocationFinger!x; let yPos =((touch?.location(in:self.superview))?. y)! - initialLocationFinger!.y; self.center = CGPoint(x:initialLocationObject!.x + xPos、y:initialLocationObject!。y + yPos);「 あなたのソリューションはよりスマートだと思うが;) –

関連する問題