Created
January 2, 2020 21:46
-
-
Save tavares1/133bbf74d799e1fb172cd471fb17f44b to your computer and use it in GitHub Desktop.
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
import UIKit | |
import PlaygroundSupport | |
protocol With {} | |
extension With where Self: AnyObject { | |
@discardableResult | |
func configure<T>(_ property: ReferenceWritableKeyPath<Self,T>, setTo value: T) -> Self { | |
self[keyPath: property] = value | |
return self | |
} | |
} | |
protocol Anchor: UIView { | |
} | |
extension Anchor { | |
func anchor<T>(referentTo referent: UIView, _ from: KeyPath<UIView,T>, equal to: KeyPath<UIView,T>, constant: CGFloat = 0, multipler: CGFloat = 0) -> Self where T: NSLayoutDimension { | |
self.translatesAutoresizingMaskIntoConstraints = false | |
self[keyPath: from].constraint(greaterThanOrEqualTo: referent[keyPath: to], multiplier: multipler, constant: constant).isActive = true | |
return self | |
} | |
func anchor<T,Axis>(referentTo referent: UIView, _ from: KeyPath<UIView,T>, equal to: KeyPath<UIView,T>, constant: CGFloat = 0, multipler: CGFloat = 0) -> Self where T: NSLayoutAnchor<Axis> { | |
self.translatesAutoresizingMaskIntoConstraints = false | |
self[keyPath: from].constraint(equalTo: referent[keyPath: to], constant: constant).isActive = true | |
return self | |
} | |
} | |
extension UIView: With, Anchor {} | |
let view = UIView() | |
.configure(\.backgroundColor, setTo: .red) | |
.configure(\.frame, setTo: CGRect(x: 0, y: 0, width: 200, height: 200)) | |
let label = UILabel() | |
.configure(\UILabel.backgroundColor, setTo: .black) | |
.configure(\.baselineAdjustment, setTo: .alignCenters) | |
.configure(\.text, setTo: "Hello World") | |
.configure(\.textColor, setTo: .white) | |
view.addSubview(label) | |
label | |
.anchor(referentTo: view, \.centerYAnchor, equal: \.centerYAnchor) | |
.anchor(referentTo: view, \.centerXAnchor, equal: \.centerXAnchor) | |
.anchor(referentTo: view, \.heightAnchor, equal: \.heightAnchor, multipler: 0.5) | |
.anchor(referentTo: view, \.widthAnchor, equal: \.widthAnchor, multipler: 0.5) | |
PlaygroundPage.current.liveView = view |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment