Stefan
Stefan

Reputation: 936

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

Upvotes: 7

Views: 6477

Answers (2)

Vasilii Muravev
Vasilii Muravev

Reputation: 3163

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
}

Upvotes: 7

Connor Neville
Connor Neville

Reputation: 7361

profileImageView hasn't been laid out yet and doesn't have a size. Presuming this is in a UIViewController subclass, you can put the corner radius code inside viewDidLayoutSubviews:

override func viewDidLayoutSubviews() {
    profileImageView.layer.cornerRadius = (profileImageView.frame.width / 2)
}

Upvotes: 0

Related Questions