Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UIButton with rounded corners and background bug

I found one weird issue with rounded UIButton.

This is my code block to create 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's a UIButton with backgroundColor, border and corner radius. It's fully rounded. But in the output I get the next appearance: rounded button with 1px border

You can see that 1px border outside the button, it's its backroundColor (black). Seems that its inner border(white) is not starting from the edje of the button.

Do you have any idea how to fix this ?

like image 321
Igor Prusyazhnyuk Avatar asked Jul 25 '16 09:07

Igor Prusyazhnyuk


1 Answers

Use CAShapeLayer instead, it also gives enhanced 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 of roundedButton, just use fillColor of CAShapeLayer.

like image 192
SHN Avatar answered Oct 19 '22 03:10

SHN