본문 바로가기
모바일앱/iOS

앱의 다크모드를 바꾸는 여러가지 방법

by GeekCode 2022. 3. 9.
반응형

 

 

 

copyright Gikko

📌 개념

IOS13

부터 다크모드가 도입되었습니다.

앱전체를 시스템설정에 따라 다크모드로 적용하는 것이라면 별 이슈가 없겠지만 아래와 같은 경우가 있을 수 있습니다.

  • 일부만 다크모드를 적용하는 경우
  • 앱 내부 설정에서 다크모드 변경을 제공하는 경우

[Common Property]

OverrideUserInterfaceStyle


→ 사용자인터페이스스타일 재정의

Apple Document

https://developer.apple.com/documentation/uikit/uiview/3238086-overrideuserinterfacestyle

var overrideUserInterfaceStyle: UIUserInterfaceStyle { get set }

Discussion

Use this property to force the view to always adopt a light or dark interface style. The default value of this property is UIUserInterfaceStyle.unspecified, which causes the view to inherit the interface style from a parent view or view controller. If you assign a different value, the new style applies to the view and all of the subviews owned by the same view controller. (If the view hierarchy contains the root view of an embedded child view controller, the child view controller and its views do not inherit the interface style.) If the view is a [UIWindow](<https://developer.apple.com/documentation/uikit/uiwindow>) object, the new style applies to everything in the window, including the root view controller and all presented content.

인터페이스 스타일을 항상 밝거나 어두운 인터페이스 스타일을 채택하려면 이 속성을 사용하세요. 이 속성의 기본 값은 parent View 혹은 ViewController에서 인터페이스 스타일을 상속합니다. 다른 값을 할당하는 경우 새 스타일이 뷰와 동일한 ViewController소유의 모든 하위뷰에 적용됩니다.

 

 

상위 ViewController나 Window가 다크모드로 되어 있더라도,

하위 View만 라이트모드로 설정할 수 있습니다.

주의할 점은 setter를 호출해줘야 한다는 점인데.

customView 안에서 override를 해서 구현하면 아예 호출이 안되는 경우가 있습니다.

override var overrideUserInterfaceStyle: UIUserInterfaceStyle {
    return .light
}

이렇게 작성했을 때 상위 ViewController의 설정을 따라가게 됩니다.

그래서 이렇게 직접 setter를 통해서 호출해주면 됩니다.

overrideUserInterfaceStyle = .light

그러면 인터페이스가 설정되는 View의 하위 View들 까지도 적용됩니다.

 

 

📌 추가적인 다크모드 설정 방법 정리

1. Info.plist 수정

Xcode 11까지

 

2022.3월 현재

 

2. AppDelegate

window 변수에 대해서 설정 가능

프로젝트 생성방법에 따라 AppDelegate 혹은 SceneDelegate에서 가능

if #available(iOS 13.0, *) {
    window?.overrideUserInterfaceStyle = .light
}

3. UIViewController

UIViewController를 개별적으로 선택 해제하려면 아래와 같이 viewDidLoad 메서드 안에 작성가능

override func viewDidLoad() {

    super.viewDidLoad()
    // overrideUserInterfaceStyle is available with iOS 13
    if #available(iOS 13.0, *) {
        // Always adopt a light interface style.
        overrideUserInterfaceStyle = .light
    }
}
반응형