Created
September 11, 2021 00:23
-
-
Save jazzychad/6d9472b6ccb9446277ac61413ac56403 to your computer and use it in GitHub Desktop.
A better way to get color values from UIColorWells
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIDebouncedColorWell.swift | |
// | |
import UIKit | |
import Combine | |
private class PublishingColor { | |
@Published var color: UIColor? = nil | |
} | |
class UIDebouncedColorWell: UIColorWell { | |
private var colorCancellable: AnyCancellable? | |
private let bgq = DispatchQueue(label: "UIColorWellDebounceQueue") | |
private let publishedColor = PublishingColor() | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
colorCancellable = publishedColor.$color | |
.debounce(for: 0.2, scheduler: bgq) | |
.sink { [weak self] someColor in | |
DispatchQueue.main.async { | |
self?.sendActions(for: .debouncedValueChanged) | |
} | |
} | |
self.addTarget(self, action: #selector(self._colorValueDidChange(sender:)), | |
for: .valueChanged) | |
} | |
@objc private func _colorValueDidChange(sender: UIColorWell) { | |
publishedColor.color = sender.selectedColor | |
} | |
} | |
extension UIControl.Event { | |
public static var debouncedValueChanged = UIControl.Event(rawValue: 99999) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment