I enhanced the anchor extension to include: centerXanchor, centerYanchor, heightAnchorEqualToWidthAnchor: Bool and centerAnchored: Bool.
I used centerAnchored in LoginController to anchor Instagram logo in the logoContainer -
let logoContainerView: UIView = {
let view = UIView()
let logoImageView = UIImageView(image: #imageLiteral(resourceName: "Instagram_logo_white"))
...
view.addSubview(logoImageView)
logoImageView.anchor(centerAnchored: true) // center Instagram logo
return view
}()
and in PreviewPhotoContainerView to center the saveLabel -
func handleSave() {
...
DispatchQueue.main.async {
...
self.addSubview(saveLabel)
saveLabel.anchor(width: 150, height: 80, centerAnchored: true) // frame?! anchor!
...
The extension anchor is a wee bit bigger:
extension UIView {
func anchor(topAnchor: NSLayoutYAxisAnchor? = nil, leftAnchor: NSLayoutXAxisAnchor? = nil, bottomAnchor: NSLayoutYAxisAnchor? = nil, rightAnchor: NSLayoutXAxisAnchor? = nil,
paddingTop: CGFloat = 0, paddingLeft: CGFloat = 0, paddingBottom: CGFloat = 0, paddingRight: CGFloat = 0, width: CGFloat = 0, height: CGFloat = 0,
centerXanchor: NSLayoutXAxisAnchor? = nil, centerYanchor: NSLayoutYAxisAnchor? = nil,
heightAnchorEqualToWidthAnchor: Bool = false,
centerAnchored: Bool = false) {
translatesAutoresizingMaskIntoConstraints = false
if let superview = superview, centerAnchored {
centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true
centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true
}
if heightAnchorEqualToWidthAnchor {
self.heightAnchor.constraint(equalTo: widthAnchor, multiplier: 1).isActive = true
}
if let topAnchor = topAnchor {
self.topAnchor.constraint(equalTo: topAnchor, constant: paddingTop).isActive = true
}
if let leftAnchor = leftAnchor {
self.leftAnchor.constraint(equalTo: leftAnchor, constant: paddingLeft).isActive = true
}
if let bottomAnchor = bottomAnchor {
self.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -paddingBottom).isActive = true
}
if let rightAnchor = rightAnchor {
self.rightAnchor.constraint(equalTo: rightAnchor, constant: -paddingRight).isActive = true
}
if let centerXanchor = centerXanchor {
self.centerXAnchor.constraint(equalTo: centerXanchor).isActive = true
}
if let centerYanchor = centerYanchor {
self.centerYAnchor.constraint(equalTo: centerYanchor).isActive = true
}
if width > 0 {
widthAnchor.constraint(equalToConstant: width).isActive = true
}
if height > 0 {
heightAnchor.constraint(equalToConstant: height).isActive = true
}
}
}
Enjoy!