iOS UIButton带圆角和背景bug

我发现圆形UIButton有一个奇怪的问题。

这是我创建此按钮的代码块。

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) 

如您所见,有一个带有backgroundColor,边框和圆角半径的UIButton。 它是全面的。 但在输出中我得到了下一个外观: 带1px边框的圆形按钮

你可以看到按钮外面的1px边框,它是它的backroundColor(黑色)。 似乎它的内边框(白色)不是从按钮的边缘开始。

你知道如何解决这个问题吗?

使用CAShapeLayer,它也提供增强的性能:

  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) 

记住不要使用roundedButton的backgroundColor,只需使用CAShapeLayer的fillColor。

向图像添加边框时也会发生这种情况。 我找不到直接解决它的方法,而是在我的图像后面添加了一个白色的UIView来实现相同的外观。

在您的情况下,在按钮后面添加一个白色UIView,具有更大的宽度和高度尺寸,以便获得所需的边框宽度(在您的情况下,它将比按钮高6 [3×2],宽6)。 然后,只需将边界半径应用于UIView和UIButton,然后vo!

我认为这是CALayer的一个错误。

我会做这样的事情:

 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)