[SWIFT 4.2]
我试图显示底部边框有这个结果:
我改进了上面帖子的扩展以添加边距..
extension UIButton {
func drawBorder(edges: [UIRectEdge], borderWidth: CGFloat, color: UIColor, margin: CGFloat) {
for item in edges {
let borderLayer: CALayer = CALayer()
borderLayer.borderColor = color.cgColor
borderLayer.borderWidth = borderWidth
switch item {
case .top:
borderLayer.frame = CGRect(x: margin, y: 0, width: frame.width - (margin*2), height: borderWidth)
case .left:
borderLayer.frame = CGRect(x: 0, y: margin, width: borderWidth, height: frame.height - (margin*2))
case .bottom:
borderLayer.frame = CGRect(x: margin, y: frame.height - borderWidth, width: frame.width - (margin*2), height: borderWidth)
case .right:
borderLayer.frame = CGRect(x: frame.width - borderWidth, y: margin, width: borderWidth, height: frame.height - (margin*2))
case .all:
drawBorder(edges: [.top, .left, .bottom, .right], borderWidth: borderWidth, color: color, margin: margin)
default:
break
}
self.layer.addSublayer(borderLayer)
}
}
}
使用:
mybutton.drawBorder(edges: [.bottom], borderWidth: 1, color: UIColor.darkGray, margin: 20)
效果很好:)