我发现圆形 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)
如您所见,有一个带有背景颜色、边框和圆角半径的 UIButton。它是完全圆形的。但是在输出中我得到了下一个外观:
你可以看到按钮外面有 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。
关于带有圆角和背景错误的 iOS UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38563850/