Last active
October 11, 2017 18:31
-
-
Save natanrolnik/e50f1006063a8079b607230f6c493730 to your computer and use it in GitHub Desktop.
Handy methods on UIView to allow easier additions of subviews (and constraints via code), only in one UIView extension
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
//: Playground - noun: a place where people can play | |
import UIKit | |
import PlaygroundSupport | |
extension UIView { | |
func addAndFitSubview(_ subview: UIView, insets: UIEdgeInsets = .zero) { | |
addSubview(subview) | |
subview.fitInSuperview(with: insets) | |
} | |
func fitInSuperview(with insets: UIEdgeInsets = .zero) { | |
guard let superview = superview else { | |
assertionFailure("fitInSuperview was called but view was not in a view hierarchy.") | |
return | |
} | |
let applyInset: (NSLayoutAttribute, UIEdgeInsets) -> CGFloat = { | |
switch $0 { | |
case .top: return $1.top | |
case .bottom: return -$1.bottom | |
case .left: return $1.left | |
case .right: return -$1.right | |
default: | |
return 0 | |
} | |
} | |
translatesAutoresizingMaskIntoConstraints = false | |
let attributes = [NSLayoutAttribute.top, .left, .right, .bottom] | |
superview.addConstraints(attributes.map { | |
return NSLayoutConstraint(item: self, | |
attribute: $0, | |
relatedBy: .equal, | |
toItem: superview, | |
attribute: $0, | |
multiplier: 1, | |
constant: applyInset($0, insets)) | |
}) | |
} | |
} | |
let myView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) | |
myView.backgroundColor = .white | |
let label = UILabel() | |
label.backgroundColor = .red | |
label.text = "Hello, Public Extensions" | |
label.textAlignment = .center | |
label.numberOfLines = 0 | |
label.font = UIFont(name: "Helvetica", size: 30) | |
//the insets parameter has a default value, so you don't need to pass insets. | |
myView.addAndFitSubview(label, insets: UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)) | |
PlaygroundPage.current.liveView = myView |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment