본문 바로가기
iOS/예제

[iOS 예제] Drag and Drop가능한 UIView만들기

by Sky Titan 2021. 12. 5.
728x90
import UIKit

class DraggableView: UIView {
 
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        moveCenter(to: touches)
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        moveCenter(to: touches)
    }
    
    private func moveCenter(to touches: Set<UITouch>) {
        guard let position = getTouchPosition(from: touches, in: superview) else { return }
        center = position
    }
    
    private func getTouchPosition(from touches: Set<UITouch>, in view: UIView?) -> CGPoint? {
        guard let touch = touches.first else { return nil }
        return touch.location(in: view)
    }
}

class DragDotView: DraggableView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    /// initialize View as a rounded red circle
    private func setupView() {
        backgroundColor = .red
        let min = min(frame.size.width, frame.size.height)
        layer.cornerRadius = min / 2
    }
}

Drag and Drop

  • UIView는 기본적으로 UIResponder를 상속받는다.
  • 때문에 touchesBegan, touchesMoved, touchesEnded 클래스 사용이 가능하다.
  • 터치 시작, 터치 움직일 때 view의 center를 해당 position으로 설정해준다.

 

 

728x90

댓글