Here is a method in which I pin a subview to a UIView
instance. Excuse the messy code, I have been experimenting trying to get this to work.
open static func withEmbeddedView(_ view: UIView, andFixedHeight height: CGFloat) -> PMGAlertControllerEmbedComponent {
let base = PMGAlertControllerEmbedComponent(frame: CGRect.zero)
base.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
base.translatesAutoresizingMaskIntoConstraints = false
let left = NSLayoutConstraint(item: view, attribute: .left, relatedBy: .equal, toItem: base, attribute: .left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal, toItem: base, attribute: .right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: base, attribute: .top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: base, attribute: .bottom, multiplier: 1, constant: 0)
base.addConstraints([left, right, top, bottom])
view.addConstraint(NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height))
base.leftConstraint = left
base.rightConstraint = right
base.topConstraint = top
base.bottomConstraint = bottom
base.layoutIfNeeded()
return base
}
Now this works fine in itself, but as soon as I try and modify these constraint's constants elsewhere, say making them 16 to add a bit of padding, the right and bottom constraints go the other way! So rather than the subview being smaller than the superview by 16pts its larger by 16pts? The top and left behave as expected.
Note that if I set the top and left to 16 but the bottom and right to -16 this produces the desired result but I shouldn't have to do this? Where am I going wrong?
Many Thanks.