Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handy methods on UIView to allow easier additions of subviews (and constraints via code)
//: 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
You can’t perform that action at this time.