Search code examples
iosswiftautolayoutsnapkit

Circular views with Autolayout (snapkit)?


I am trying to make a circular view which has an adaptive size based on auto layout, currently i set the constraints, then i attempt to round the image in the viewwilllayoutsubviews method.

This is resulting in oddly shaped views that are not circular, how can i resolve this?

init:

    profilePic = UIImageView(frame: CGRect.zero)
    profilePic.clipsToBounds = true
    profilePic.contentMode = .scaleAspectFill

constrains:

 profilePic.snp.makeConstraints { (make) -> Void in
                make.centerX.equalTo(self).multipliedBy(0.80)
                make.centerY.equalTo(self).multipliedBy(0.40)
                make.size.equalTo(self).multipliedBy(0.22)
            }

subviews:

override func viewWillLayoutSubviews() {
        self.navigationMenuView.profilePic.layer.cornerRadius = self.navigationMenuView.profilePic.frame.size.width / 2.0
        self.navigationMenuView.profilePic.layer.borderWidth = 2
        self.navigationMenuView.profilePic.layer.borderColor = UIColor.white.cgColor
    }

result:

enter image description here


Solution

  • I guess you want this (sorry for the plain autolayout, but I don't use snapkit):

    profilePic.heightAnchor.constraint(equalTo: profilePic.widthAnchor).isActive = true
    profilePic.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.22).isActive = true
    

    Instead of this:

    make.size.equalTo(self).multipliedBy(0.22)