IOS UIButton with rounded corners and background error

I found one strange problem with rounded UIButton.

This is my code for creating this button.

let roundedButton = UIButton(type: .System) roundedButton.frame = CGRectMake(100, 100, 100, 100) roundedButton.backgroundColor = UIColor.blackColor() roundedButton.layer.borderColor = UIColor.whiteColor().CGColor roundedButton.layer.borderWidth = 3.0 roundedButton.layer.cornerRadius = roundedButton.frame.size.width/2 roundedButton.layer.masksToBounds = true self.view.addSubview(roundedButton) 

As you can see, there is a UIButton with backgroundColor, border and angular radius. It is fully rounded. But in the output, I get the following view: rounded button with 1px border

You can see that the 1px border is outside the button, this is its backroundColor (black). It seems that its inner border (white) does not start with the edje button.

Do you have an idea how to fix this?

+6
source share
3 answers

Use CAShapeLayer instead, as well as improved performance:

  let roundedButton = UIButton(type: .Custom) roundedButton.frame = CGRectMake(100, 100, 100, 100) let _border = CAShapeLayer() _border.path = UIBezierPath(roundedRect: roundedButton.bounds, cornerRadius:roundedButton.frame.size.width/2).CGPath _border.frame = roundedButton.bounds _border.strokeColor = UIColor.whiteColor().CGColor _border.fillColor = UIColor.blackColor().CGColor _border.lineWidth = 3.0 roundedButton.layer.addSublayer(_border) self.view.addSubview(roundedButton) 

Remember not to use backgroundColor roundedButton, just use fillColor for CAShapeLayer.

+2
source

This also happens when adding borders to images. I could not find a way to solve it directly, but instead I added a white UIView behind my image to achieve the same look.

In your case, add a white UIView behind the button, with large widths and heights to achieve the desired border width (in your case it will be 6 [3x2] higher than the button and 6 wider). Then just apply the border radius to both the UIView and the UIButton and voilร !

0
source

I think this is a bug with CALayer .

I would do something like this:

 let borderWidth: CGFloat = 3.0 let roundedButton = UIButton(type: .System) roundedButton.frame = CGRectMake(100, 100, 100, 100) roundedButton.layer.cornerRadius = roundedButton.frame.size.width / 2 roundedButton.layer.backgroundColor = UIColor.whiteColor().CGColor roundedButton.layer.masksToBounds = true let innerLayer = CALayer() innerLayer.frame = CGRect( x: borderWidth, y: borderWidth, width: roundedButton.frame.width - borderWidth * 2, height: roundedButton.frame.height - borderWidth * 2 ) innerLayer.backgroundColor = UIColor.blackColor().CGColor innerLayer.cornerRadius = innerLayer.frame.size.width / 2 roundedButton.layer.addSublayer(innerLayer) 
0
source

All Articles