Skip to content

Instantly share code, notes, and snippets.

@jazzychad
Created September 11, 2021 00:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jazzychad/6d9472b6ccb9446277ac61413ac56403 to your computer and use it in GitHub Desktop.
Save jazzychad/6d9472b6ccb9446277ac61413ac56403 to your computer and use it in GitHub Desktop.
A better way to get color values from UIColorWells
//
// 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