iOS/코드조각

[iOS, Swift] UIRotationGestureRecognizer 예제

검은참깨두유vm 2022. 8. 25. 11:00
반응형

iOS 15.5, Xcode 13.31, Swift 5, UIKit 환경에서 진행했습니다.

 

import UIKit

class UIRotationViewController: UIViewController {
    
    lazy var label: UILabel = {
       var label = UILabel()
        label.text = "rotate test"
        label.frame = CGRect(x: 50, y: 50, width: 200, height: 50)
        label.backgroundColor = .red
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(label)
        
        let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(handleRotate(_:)))
        view.addGestureRecognizer(rotateGesture)
    }
    
    @objc func handleRotate(_ gesture: UIRotationGestureRecognizer) {
        if gesture.state == UIGestureRecognizer.State.changed {
            let transform = CGAffineTransform(rotationAngle: gesture.rotation)
            view.transform = transform
        }
    }
}

Rotate 기능을 사용하고 싶은 View에 addGestureRecognizer 메소드를 통해 Gesture를 등록하여 Rotate 기능을 사용할 수 있다.

 

반응형