Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] UIPinchGestureRecognizer 개념 (줌 기능, zoom) 본문

iOS 응용 (swift)

[iOS - swift] UIPinchGestureRecognizer 개념 (줌 기능, zoom)

jake-kim 2023. 12. 22. 23:10

UIPinchGestureRecognizer로 구현한 줌 기능

UIPinchGestureRecognizer 개념

  • 애플에서는 pinch이라는 단어는 일반적으로 사용자가 "줌"하는 행위를 의미

https://developer.apple.com/documentation/uikit/uipinchgesturerecognizer

  • UIPinchGestureRecognizer를 사용하여 줌 기능 적용이 가능

줌기능 (Pinching) 구현

  • 파란색 뷰 준비
import UIKit

class ViewController: UIViewController {
    private let blueView = {
        let view = UIView()
        view.backgroundColor = .blue
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(blueView)
        
        NSLayoutConstraint.activate([
            blueView.heightAnchor.constraint(equalToConstant: 200),
            blueView.widthAnchor.constraint(equalToConstant: 300),
            blueView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            blueView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        ])
    }
}
  • 파란색 밖의 뷰 영역을 pincing해도 파란색 뷰의 영역 크기가 조절되어야 하므로 gesture를 self.view에 등록
let gesture = UIPinchGestureRecognizer(target: self, action: #selector(zooming))
view.addGestureRecognizer(gesture)
  • 줌 기능 구현
@objc
private func zooming(_ gesture: UIPinchGestureRecognizer) {

}
  • UIGestureRecognizer가 가지고 있는 제스처의 상태 값, gesture.state를 사용하여 changed에서 처리
@objc
private func zooming(_ gesture: UIPinchGestureRecognizer) {
    switch gesture.state {
    case .changed:
        let changedScaleTransform = CGAffineTransform(scaleX: gesture.scale, y: gesture.scale)
        let minBound = 0.1
        let maxBound = 3.0
        
        guard (minBound...maxBound) ~= changedScaleTransform.a else { break }
        blueView.transform = changedScaleTransform
        
    default:
        break
    }
}

완성)

* 전체 코드: https://github.com/JK0369/ExPinchRecognizer

* 참고

- https://developer.apple.com/documentation/uikit/touches_presses_and_gestures/handling_uikit_gestures/handling_pinch_gestures

- https://developer.apple.com/documentation/uikit/uipinchgesturerecognizer

Comments