Reputation: 1048
I have a few views whose size is not hardcoded, but determined via constraints and I need those views to be round.
Is there a way to set the cornerRadius property "dynamically", e.g. depending on the actual size of the object?
I know that if this view is inside a UIViewController, I can get the width via roundView.frame.width
and set the layer.cornerRadius property there, but the round views aren't contained in a viewController, but managed by another simple UIView.
Thank you in advance!
Dave
Upvotes: 3
Views: 2341
Reputation: 4008
Easy to achieve this with RxSwift by observing Key Path.
extension UIView{
func cornerHalf(){
clipsToBounds = true
rx.observe(CGRect.self, #keyPath(UIView.bounds))
.subscribe(onNext: { _ in
self.layer.cornerRadius = self.bounds.width * 0.5
}).disposed(by: rx.disposeBag)
}
}
Just call in init
method, the code seems simpler by declaration , instead of being distributed two place. Especially, the logic is commonly exsited in your project.
Call like this:
let update: UIButton = {
let btn = UIButton()
// more config
btn.cornerHalf()
return btn
}()
Upvotes: 1
Reputation: 2666
You can override layoutSubviews method of View class and set the cornerRadius value there. Lets say you want cornerRadius to be half of width of the view:
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.bounds.width * 0.5
}
Upvotes: 9
Reputation: 342
Just access them through your simple view that contains them. If your simple container view doesn't have those round view as instances, then you can access them by iterating through its subviews array. When you get a hold of the view you can access their frame.size.width and set the layer.corner radius property to that value.
Upvotes: 0