Last active
February 6, 2022 13:53
-
-
Save natanrolnik/818d83c5923b4621233e2c6396397819 to your computer and use it in GitHub Desktop.
Handy methods on UIView to allow easier additions of subviews (and constraints via code)
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 NSLayoutConstraint { | |
func applyInset(_ insets: UIEdgeInsets) -> NSLayoutConstraint { | |
guard firstAttribute == secondAttribute else { | |
return self | |
} | |
switch firstAttribute { | |
case .top: constant = insets.top | |
case .bottom: constant = -insets.bottom | |
case .left: constant = insets.left | |
case .right: constant = -insets.right | |
default: | |
break | |
} | |
return self | |
} | |
} | |
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 | |
} | |
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: 0).applyInset(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