Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

layer.cornerRadius not working in conjunction with NSLayoutConstraints (swift 3)

Below are my profile view constraints and the view renders well, however the width consistently returns zero. So that final constraint, profileImageView.layer.cornerRadius = (profile.frame.width / 2) returns zero everytime.

    profileImageView.translatesAutoresizingMaskIntoConstraints = false


    addConstraint(NSLayoutConstraint(item: profileImageView, attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 0.125, constant: 0))


    addConstraint(NSLayoutConstraint(item: profileImageView, attribute: .height, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 0.125, constant: 0))




    addConstraint(NSLayoutConstraint(item: profileImageView, attribute: .centerY, relatedBy: .equal, toItem: containerView, attribute: .centerY, multiplier: 1, constant: 0))

    addConstraint(NSLayoutConstraint(item: profileImageView, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 0.25, constant: 0))

    profileImageView.layer.cornerRadius = (profileImageView.frame.width / 2)

Any suggestions?

enter image description here

like image 449
Stefan Avatar asked May 10 '17 19:05

Stefan


1 Answers

profileImageView.frame.width is zero, because of it's frame isn't calculated yet. Inside your profileImageView override layoutSubviews method:

override func layoutSubviews() {
    super.layoutSubviews()
    layer.cornerRadius = bounds.width / 2.0
}

Or if you're using view controller, override viewDidLayoutSubviews method:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    profileImageView.layer.cornerRadius = profileImageView.bounds.width / 2.0
}
like image 185
Vasilii Muravev Avatar answered Sep 30 '22 19:09

Vasilii Muravev