Skip to content

Instantly share code, notes, and snippets.

@AndresR173
Last active January 9, 2020 17:03
Show Gist options
  • Save AndresR173/080baa91d6d2d50e06b7886aeab77f35 to your computer and use it in GitHub Desktop.
Save AndresR173/080baa91d6d2d50e06b7886aeab77f35 to your computer and use it in GitHub Desktop.
Builder Pattern
protocol Builder {
typealias Handler = (inout Self) -> Void
}
extension NSObject: Builder {}
extension Builder {
public func with(_ configure: Handler) -> Self {
var this = self
configure(&this)
return this
}
}
extension Builder where Self: UIView {
func usingAutoLayout() -> Self {
self.translatesAutoresizingMaskIntoConstraints = false
return self
}
func userInteractionDisabled() -> Self {
self.isUserInteractionEnabled = false
return self
}
func userInteractionEnabled() -> Self {
self.isUserInteractionEnabled = true
return self
}
}
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
// Without usgin builder
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
// With builder
let label2 = UILabel()
.usingAutoLayout()
.userInteractionDisabled()
.with() {
$0.text = "Label"
$0.textColor = .blue
}
view.addSubview(label)
view.addSubview(label2)
NSLayoutConstraint.activate([
label2.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 8),
label2.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
self.view = view
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment