Skip to content

Instantly share code, notes, and snippets.

@b3ll
Last active February 1, 2021 12:50
Show Gist options
  • Save b3ll/b317d463fa3f9ebaee5d41c6a8dcfc32 to your computer and use it in GitHub Desktop.
Save b3ll/b317d463fa3f9ebaee5d41c6a8dcfc32 to your computer and use it in GitHub Desktop.
@propertyWrapper
public final class LayoutInvalidating<Value> where Value: Equatable {
public static subscript<EnclosingSelf>(
_enclosingInstance observed: EnclosingSelf,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<EnclosingSelf, LayoutInvalidating>
) -> Value where EnclosingSelf: UIView {
get {
return observed[keyPath: storageKeyPath].stored
}
set {
let oldValue = observed[keyPath: storageKeyPath].stored
observed[keyPath: storageKeyPath].stored = newValue
if newValue != oldValue {
observed.setNeedsLayout()
}
}
}
public var wrappedValue: Value {
get { fatalError("called wrappedValue getter") }
set { fatalError("called wrappedValue setter") }
}
public init(wrappedValue: Value) {
self.stored = wrappedValue
}
// MARK: - Private
private var stored: Value
}
// Test for Playgrounds
public class SomeView: UIView {
@LayoutInvalidating public var volume: CGFloat = 0.0
}
let a = SomeView(frame: .zero)
a.volume = 20.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment