Trouble Shooting

[iOS] 디바이스 회전을 감지하는 notification

나른한코딩 2022. 8. 16. 17:17

 

 

Trouble

- 특정 라이브러리를 사용시, 화면이 회전되면 cell이 옆으로 밀리는 이슈가 있었다.

- 라이브러리의 고질적인 문제로 라이브러리를 뜯어 고치지 않는 이상 해결이 불가능하였다.

 

 

Shooting

- 그래서 생각한 방법은 두가지 이다.

1. 화면 회전을 막는다.

2. 화면 회전을 감지하여 화면이 회전되는 시점에 데이터를 refresh 해주는 작업을 해준다.

 

만약 기회의도가 화면 회전이 가능하도록 되어있다면

특정 기능에 문제가 생긴다고 하여 기능을 막아버리는 것은 옳지 않다.

그래서 아래 코드의 some code... 부분에 데이터를 가지고 뷰를 refresh 해주는 코드를 추가하여 해결하였다.

(그 반대의 경우라면 회전을 막으면 깔끔)

 

 

 

화면 회전을 감지하는 옵저버를 추가하는 코드는 다음과 같다. 필요시 참고해보자.

 

override func viewDidLoad() {
	super.viewDidLoad()
    
    addObservers() // 옵저버 추가
}

deinit {
	removeObservers() // deinit 시점에 옵저버 제거
}

func addObservers() {
    NotificationCenter.default.addObserver(self, selector: #selector(self.detectOrientation), name: NSNotification.Name("UIDeviceOrientationDidChangeNotification"), object: nil)
}
    
func removeObservers() {
    NotificationCenter.default.removeObserver(NSNotification.Name("UIDeviceOrientationDidChangeNotification"))
}
    
/// 디바이스 회전 감지 함수
@objc func detectOrientation() {
    if (UIDevice.current.orientation == .landscapeLeft) || (UIDevice.current.orientation == .landscapeRight) {
        print("회전 감지 : landscapeLeft")
        // some code ...
    } else if (UIDevice.current.orientation == .portrait) || (UIDevice.current.orientation == .portraitUpsideDown) {
        print("회전 감지 : portrait")
        // some code ...
    }
}

 

 

 

반응형