Shouldn\'t there be a way to resize the frame of a UIView after you\'ve added subviews so that the frame is the size needed to enclose all the subviews? If your subviews are
Although quite a few answers already, none worked for my use case. In case you use autoresizingMasks and want to resize view and move subviews so the size of rectangle matches subviews.
public extension UIView {
func resizeToFitSubviews() {
var x = width
var y = height
var rect = CGRect.zero
subviews.forEach { subview in
rect = rect.union(subview.frame)
x = subview.frame.x < x ? subview.frame.x : x
y = subview.frame.y < y ? subview.frame.y : y
}
var masks = [UIView.AutoresizingMask]()
subviews.forEach { (subview: UIView) in
masks.add(subview.autoresizingMask)
subview.autoresizingMask = []
subview.frame = subview.frame.offsetBy(dx: -x, dy: -y)
}
rect.size.width -= x
rect.size.height -= y
frame.size = rect.size
subviews.enumerated().forEach { index, subview in
subview.autoresizingMask = masks[index]
}
}
}