2016-10-05 2 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; yPos = ((터치? 위치 (in : self.superview)) ?. y)! - initialLocationFinger! .y; 그러나 나는 당신의 솔루션이 더 똑똑하다고 생각합니다;) –

관련 문제