[swift] SnapKit으로 앱 내 테마 변경하기

앱 개발 중에는 사용자가 테마를 변경할 수 있는 기능을 구현해야 할 때가 있습니다. SnapKit은 Swift에서 사용하기 쉬운 오픈 소스 라이브러리로, 앱 내 요소들의 레이아웃을 쉽게 구성할 수 있게 도와줍니다. 이번 블로그 포스트에서는 SnapKit을 사용하여 앱 내 테마를 변경하는 방법에 대해 알아보겠습니다.

1. SnapKit 설치하기

먼저, 프로젝트에 SnapKit을 설치해야 합니다. Cocoapods를 사용하여 설치하는 방법은 아래와 같습니다.

pod 'SnapKit'

설치가 완료되면 프로젝트를 빌드하고 Xcode를 재실행합니다.

2. 테마 관리 클래스 만들기

테마 관리에 필요한 클래스를 만들어야 합니다. 이 클래스에서는 각각의 테마에 대한 색상, 폰트, 이미지 등을 관리합니다. 예를 들어, ThemeManager 클래스를 만들고 다음과 같이 구성할 수 있습니다.

class ThemeManager {
    static let shared = ThemeManager()

    var backgroundColor: UIColor {
        switch currentTheme {
        case .light:
            return .white
        case .dark:
            return .black
        }
    }

    var textColor: UIColor {
        switch currentTheme {
        case .light:
            return .black
        case .dark:
            return .white
        }
    }

    // 다른 테마 관련 속성들...

    var currentTheme: Theme = .light {
        didSet {
            NotificationCenter.default.post(name: .themeDidChange, object: nil)
        }
    }

    private init() {}
}

여기서 Theme은 열거형으로 테마 옵션을 정의하며, NotificationCenter를 사용하여 테마가 변경되었음을 앱 내의 다른 요소들에 알립니다.

3. 테마 적용하기

SnapKit을 사용하여 앱 내 요소들에 테마를 적용할 수 있습니다. 예를 들어, MyView 클래스에서는 텍스트 색상과 배경 색상을 테마 관리 클래스의 속성에 따라 설정할 수 있습니다.

class MyView: UIView {
    private let label = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
        setupConstraints()
        applyTheme()
        NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeDidChange, object: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupView() {
        // 뷰와 라벨 설정...
    }

    private func setupConstraints() {
        // 제약조건 설정...
    }

    @objc private func themeDidChange() {
        applyTheme()
    }

    private func applyTheme() {
        backgroundColor = ThemeManager.shared.backgroundColor
        label.textColor = ThemeManager.shared.textColor
    }
}

위의 예제에서는 applyTheme() 메소드를 따로 호출하여 처음에 한번 그리고 테마가 변경될 때마다 호출하여 테마를 적용합니다.

4. 테마 변경하기

마지막으로, 사용자가 테마를 변경할 수 있는 앱 내 설정 메뉴를 구성해야 합니다. 예를 들어, SettingsViewController에서는 사용자가 테마를 선택할 수 있는 목록을 제공할 수 있습니다.

class SettingsViewController: UIViewController {
    private let themeOptions = ["Light", "Dark", "Custom"]

    // 다른 뷰 컨트롤러 레이아웃 및 기능...

    private func showThemePicker() {
        let alertController = UIAlertController(title: "Select Theme", message: nil, preferredStyle: .actionSheet)
        
        for theme in themeOptions {
            let action = UIAlertAction(title: theme, style: .default) { [weak self] _ in
                self?.changeTheme(theme)
            }
            alertController.addAction(action)
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)

        present(alertController, animated: true, completion: nil)
    }

    private func changeTheme(_ theme: String) {
        switch theme {
        case "Light":
            ThemeManager.shared.currentTheme = .light
        case "Dark":
            ThemeManager.shared.currentTheme = .dark
        case "Custom":
            // 사용자 정의 테마 적용
            break
        default:
            break
        }
    }
}

위의 예제에서는 알림 센터를 통해서 themeDidChange를 수신하고 해당 메소드에 응답하여 선택한 테마를 반영합니다. MyView와 같은 다른 요소들도 테마 변경을 감지하여 자동으로 업데이트됩니다.

SnapKit을 사용하여 앱 내에서 테마를 변경하는 방법을 알아보았습니다. 이제 깔끔하고 일관된 사용자 경험을 제공하기 위해 앱에 테마 기능을 추가할 수 있습니다.