Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags
more
Archives
Today
Total
관리 메뉴

iOS 개발일지

UIView 객체를 드래그를 통해 이동시키자! (feat. UIPanGestureRecognizer) 본문

iOS - 코드블럭 아카이브

UIView 객체를 드래그를 통해 이동시키자! (feat. UIPanGestureRecognizer)

Lia's iOS 2023. 5. 18. 08:51

 

// 주의! 제스쳐를 추가할 버튼마다 제스쳐를 생성해주어야 한다.
// 같은 타겟과 액션을 가진 제스쳐라도 하나씩 등록하지 않으면 제대로 동작하지 않는다.
        let panGestureStateButton = UIPanGestureRecognizer(target: self, action: #selector(dragButton))
        stateButton.addGestureRecognizer(panGestureStateButton)
        let panGestureCountButton = UIPanGestureRecognizer(target: self, action: #selector(dragButton))
        countButton.addGestureRecognizer(panGestureCountButton)

    @objc func dragButton(sender: UIPanGestureRecognizer) {
        let translation = sender.translation(in: self)
        guard let button = sender.view else { return }

        // 슈퍼뷰 경계 내에서만 움직이도록 제한
        let superViewBounds = self.bounds
        let buttonSize = button.bounds.size
        let newY = button.center.y + translation.y
        let minY = buttonSize.height / 2
        let maxY = superViewBounds.height - buttonSize.height / 2
        
        // 수평 이동 금지하여 위아래로만 움직이도록 제한 (X 좌표는 현재 위치를 유지)
	// 수평 이동을 허용하고 싶다면 clampedX도 동적인 값으로 변경
        let clampedX = button.center.x
        let clampedY = min(max(newY, minY), maxY)
        
        button.center = CGPoint(x: clampedX, y: clampedY)
        sender.setTranslation(.zero, in: self)
    }