Reputation: 411
I am working on screen where I want to make this profile view circular. But I am not getting height or width from imageView.frame.height
to use it in layer.cornerRadius
. Please help me. Thanks.
Here is the code for reference.
private func addImageView() {
topView.addSubview(profilePicView)
NSLayoutConstraint.activate([
profilePicView.centerXAnchor.constraint(equalTo: topView.centerXAnchor),
profilePicView.widthAnchor.constraint(equalTo: topView.heightAnchor, multiplier: 0.3)
])
profilePicViewTopAnchor = profilePicView.topAnchor.constraint(equalTo: view.topAnchor, constant: 64)
profilePicViewTopAnchor?.isActive = true
profilePicViewHeightAnchor = profilePicView.heightAnchor.constraint(equalTo: topView.heightAnchor, multiplier: 0.3)
profilePicViewHeightAnchor?.isActive = true
}
And I am trying to get values as,
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print((profilePicViewHeightAnchor?.constant)!)
profilePicView.layer.cornerRadius = (profilePicViewHeightAnchor?.constant)! / 2
profilePicView.clipsToBounds = true
}
SOLVED
After everyones help I got this solution which works perfectly fine for me,
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let radius = redView.frame.height * 0.3
profilePicView.layer.cornerRadius = radius / 2
profilePicView.clipsToBounds = true
self.view.layoutIfNeeded()
}
Thanks to all you guys. Really appreciated the help.
Upvotes: 5
Views: 2760
Reputation: 26
you can Also use ViewDidAppear.because at this time Autolayout engine started to layout Constraint.
override func viewDidAppear() {
super.viewDidAppear()
print(imageView.frame.height)
}
Upvotes: 0
Reputation: 1698
Try this extension:
extension UIView {
@IBInspectable
/// Should the corner be as circle
public var circleCorner: Bool {
get {
return min(bounds.size.height, bounds.size.width) / 2 == cornerRadius
}
set {
cornerRadius = newValue ? min(bounds.size.height, bounds.size.width) / 2 : cornerRadius
}
}
}
Upvotes: -1
Reputation: 15248
This must be because the time you are accessing the frame
for imageView
, the layout constraints are not laid out by the autolayout
. So, If your imageView
is inside a UIViewController
class then you should override
the below method and then access the width
and height
.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print(imageView.frame.height)
}
If imageView
is inside a custom view then you can override
the below method and then access the frame
,
override func layoutSubviews() {
super.layoutSubviews()
print(imageView.frame.height)
}
Upvotes: 6
Reputation: 2962
You can try to set in storyboard on identifier inspector. like
Upvotes: 0
Reputation: 1055
Please try this it helps to you.
imageView.layer.cornerRadius = imageView.frame.size.height / 2
imageView.clipsToBounds = true
Make sure your height and width of imageView is same. Thanks
Upvotes: 0