带有圆角和背景错误的 iOS UIButton

标签 ios swift uibutton border cornerradius

我发现圆形 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。它是完全圆形的。但是在输出中我得到了下一个外观: rounded button with 1px border

你可以看到按钮外面有 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/

相关文章:

ios - 自定义表格单元格: "class is not key value coding-compliant"

swift - 在 Swift 中使用自动换行自动调整多行 UILabel

ios - Swift:在没有 TabBar 和 NavigationBar 的情况下裁剪屏幕截图

ios - 是否可以让多个 UIButton 打开一个 tableviewcontroller?

android - 来自 SDK 的崩溃分析

ios - WinObjC:如何知道支持/处理哪些 cocoa 框架?

ios - UIImage+Resize 类别扩展错误和警告 iOS 7

swift - 使用通用函数获取核心数据实体亲属

ios - 单击时更新标签

uitableview - 从选定行获取 PFObject 并保存到另一个解析类