Reputation: 101
I am trying to set the cornerRadius
of a UIButton
so that it looks like circular , but I am not able to do it .
Here is the code for what I have tried.
func addColorButton() {
let colorButton : UIButton = {
let cb = UIButton()
cb.translatesAutoresizingMaskIntoConstraints = false
cb.backgroundColor = .black
return cb
}()
view.addSubview(colorButton)
colorButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
colorButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10).isActive = true
colorButton.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5).isActive = true
colorButton.heightAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5).isActive = true
colorButton.layer.cornerRadius = 0.5 * colorButton.bounds.size.width
print(colorButton.bounds.width)
colorButton.clipsToBounds = true
}
override func viewDidLoad() {
super.viewDidLoad()
addColorButton()
}
Upvotes: 1
Views: 499
Reputation: 256
You can create simple subclass which can use whenever you need
I just show reference of UIButton with shadow and round corner , You can make it IBInspectable to use these properties from storyboard though .
class UIButtonShadow: UIButton {
var yPos : CGFloat = 2 {
didSet {
addBehavior()
}
}
var radius : CGFloat = 2 {
didSet {
addBehavior()
}
}
var cornerRadius : CGFloat = 18 {
didSet {
addBehavior()
}
}
override var bounds: CGRect {
didSet {
addBehavior()
}
}
override var frame: CGRect{
didSet{
addBehavior()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addBehavior()
}
override func awakeFromNib() {
super.awakeFromNib()
addBehavior()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func addBehavior() {
self.layer.cornerRadius = cornerRadius
let shadowPath = UIBezierPath(roundedRect:self.bounds,cornerRadius:self.layer.cornerRadius)
self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width:0.0,height:yPos)
self.layer.shadowOpacity = 0.3
self.layer.shadowPath = shadowPath.cgPath
self.layer.shadowRadius = radius
}
}
Upvotes: 0
Reputation: 86
I think you need to use masksToBounds for this.
colorButton.layer.masksToBounds = true
Upvotes: 0
Reputation: 16160
The buttons bounds/frame won't set until autolayout completed. You could update,
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Update corner radius here
colorButton.layer.cornerRadius = 0.5 * colorButton.bounds.size.width
}
Upvotes: 4