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
'iOS > 예제' 카테고리의 다른 글
[iOS 예제] CircleProgressView 만들기 (0) | 2021.12.11 |
---|---|
[iOS 예제] UIView에 원형으로 shadow 넣기 (0) | 2021.12.07 |
[iOS 예제] InfiniteTextView 무한 스크롤 텍스트뷰 만들기 (0) | 2021.06.17 |
[iOS 예제] UIPanGestureRecognizer로 BottomSheet 만들어보기 (0) | 2021.05.01 |
[iOS 예제] CircleProgress Shape 만들기 (0) | 2021.04.30 |
댓글