mastodon-ios/Mastodon/Scene/Settings/Cell/SettingsAppearanceTableView...

73 lines
2.3 KiB
Swift
Raw Normal View History

2022-02-08 11:17:17 +01:00
//
// SettingsAppearanceTableViewCell+ViewModel.swift
// Mastodon
//
// Created by MainasuK on 2022-2-8.
//
import UIKit
import Combine
import CoreDataStack
extension SettingsAppearanceTableViewCell {
final class ViewModel: ObservableObject {
var disposeBag = Set<AnyCancellable>()
private var observations = Set<NSKeyValueObservation>()
// input
@Published public var customUserInterfaceStyle: UIUserInterfaceStyle = .unspecified
@Published public var preferredTrueBlackDarkMode = false
// output
@Published public var appearanceMode: SettingsItem.AppearanceMode = .system
init() {
UserDefaults.shared.observe(\.customUserInterfaceStyle, options: [.initial, .new]) { [weak self] defaults, _ in
guard let self = self else { return }
self.customUserInterfaceStyle = defaults.customUserInterfaceStyle
}
.store(in: &observations)
}
public func prepareForReuse() {
// do nothing
}
}
}
extension SettingsAppearanceTableViewCell.ViewModel {
func bind(cell: SettingsAppearanceTableViewCell) {
Publishers.CombineLatest(
2022-02-08 12:50:18 +01:00
$customUserInterfaceStyle.removeDuplicates(),
$preferredTrueBlackDarkMode.removeDuplicates()
2022-02-08 11:17:17 +01:00
)
2022-02-08 12:50:18 +01:00
.debounce(for: 0.1, scheduler: DispatchQueue.main)
.receive(on: DispatchQueue.main)
2022-02-08 11:17:17 +01:00
.sink { customUserInterfaceStyle, preferredTrueBlackDarkMode in
cell.appearanceViews.forEach { view in
view.selected = false
}
switch customUserInterfaceStyle {
case .unspecified:
cell.systemAppearanceView.selected = true
case .dark:
2022-02-14 12:57:15 +01:00
cell.darkAppearanceView.selected = true
2022-02-08 11:17:17 +01:00
case .light:
cell.lightAppearanceView.selected = true
@unknown default:
assertionFailure()
}
}
.store(in: &disposeBag)
}
}
extension SettingsAppearanceTableViewCell {
func configure(setting: Setting) {
setting.publisher(for: \.preferredTrueBlackDarkMode)
.assign(to: \.preferredTrueBlackDarkMode, on: viewModel)
.store(in: &disposeBag)
}
}