Reputation: 7414
I have a UIButton
within a UIView
with two constraints. Both constraints were set in Interface Builder so that the UIButton
is centered vertically and horizontally in its superview.
I wanted to add a border to the UIButton
and make it rounded. Having followed an answer on SO I was able to get the button partially rounded.
For some reason though, the button is not really round. I assume this is because of my height & width not being equal to each other. Each time I set the width/height of the button to be equal, the autolayout constraints reset it back to 40x34.
I am using the following code to create the rounded button.
self.startButton.clipsToBounds = true
self.startButton.layer.cornerRadius = self.startButton.frame.height / 2
self.startButton.layer.borderWidth = 1
self.startButton.layer.borderColor = self.view.tintColor.CGColor
self.startButton.layer.shadowRadius = 6.0
self.startButton.layer.shadowColor = UIColor.blackColor().CGColor
self.startButton.layer.shadowOffset = CGSizeMake(0.0, 3.0)
self.startButton.layer.shadowOpacity = 0.65
Why does having my button centered vertically and horizontally prevent me from changing its size? I don't understand why I can't set the size of the button and have the constraints re-center it based on the size values I assign to it.
I have moved the code in to the viewDidLayoutSubviews
and then modified the constraints so that both the height and width are constrained to 40x40.
override func viewDidLayoutSubviews() {
self.startButton.clipsToBounds = true
self.startButton.titleLabel?.text = "Start"
self.startButton.layer.cornerRadius = self.startButton.frame.height / 2
self.startButton.layer.borderWidth = 1
self.startButton.layer.borderColor = self.view.tintColor.CGColor
self.startButton.layer.shadowRadius = 6.0
self.startButton.layer.shadowColor = UIColor.blackColor().CGColor
self.startButton.layer.shadowOffset = CGSizeMake(0.0, 3.0)
self.startButton.layer.shadowOpacity = 0.65
}
This partially solves my problem; not fully though. If I do not assign a value to the titleLabel
, then the button is a proper round button.
However, if I assign a value to the titleLabel
, the button becomes a rounded rect and is not a circle.
The text does not appear in the button though, which confuses me. I need to have the button be a circle, scaling to fit the content it has as well. My button type is set to Custom
. I don't know if that has any effect on this as well.
After doing some testing, I discovered i was setting the edge insets to the button. Once I removed the following:
self.startButton.contentEdgeInsets = UIEdgeInsets(top: 25, left: 25, bottom: 25, right: 25)
I got the desired effect with @Leo's answer.
Upvotes: 0
Views: 47
Reputation: 24714
You need to add constraints about height & width of your button.
Either fixed width & height,or aspect radio is ok.
If you use aspect radio,set up the corner radius in viewDidLayoutSubviews
Upvotes: 1