I'm trying to programmatically create a view that is centered inside a designated superview. I can almost achieve this behavior, however the centered view does not respect the dynamic height of its content. Here is the function I created to make it happen:
static func overlayWithButton(onView view: UIView, buttonText: String, theme: Theme = .dark, action: Action? = nil) -> UIView {
// create overlay
let overlay = UIView()
overlay.translatesAutoresizingMaskIntoConstraints = false
let leftInset: CGFloat = 20
let rightInset: CGFloat = 20
// Style overlay
overlay.backgroundColor = theme == .dark ? UIColor.black : UIColor.white
overlay.alpha = 0.75
overlay.cornerRadius = 10
// create button
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
button.translatesAutoresizingMaskIntoConstraints = false
// Style Button
button.backgroundColor = UIColor.clear
button.setTitle(buttonText, for: .normal)
button.setTitleColor(theme == .dark ? lightBlueButtonText : UIColor.black, for: .normal)
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.titleLabel?.numberOfLines = 0
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.isEnabled = true
// add button action
if let action = action {
button.add(for: .touchUpInside, action)
}
// add constraints
overlay.addSubview(button)
button.centerXAnchor.constraint(equalTo: overlay.centerXAnchor).isActive = true
button.leftAnchor.constraint(greaterThanOrEqualTo: overlay.leftAnchor).isActive = true
button.rightAnchor.constraint(lessThanOrEqualTo: overlay.rightAnchor).isActive = true
button.topAnchor.constraint(equalTo: overlay.topAnchor).isActive = true
button.bottomAnchor.constraint(equalTo: overlay.bottomAnchor).isActive = true
view.addSubview(overlay)
overlay.leftAnchor.constraint(equalTo: view.leftAnchor, constant: leftInset).isActive = true
overlay.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -rightInset).isActive = true
overlay.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
return overlay
}
This works with short button titles:
However, with longer title, the button content is clipped:
Using reveal I can see that the title / button label is responding as intended.
I've been at this for quite a while now, and I can't get the centered overlay to expand its height to match the intrinsic content size of its contents. Any ideas?