斯威夫特的负角落

时间:2018-04-17 07:23:32

标签: swift label swift4

我想在Swift中设计一个被标签包围的按钮。

有人知道如何设计负面的圆形标签,如下图所示吗?

enter image description here

1 个答案:

答案 0 :(得分:3)

制作这个的正确方法是制作一个Bezierpath并将其指定为UIView的子层。

我要使用的代码将使用UIView。在此视图内部创建一个标签或子类UILabel而不是UIView以获得所需的结果。

示例代码如下:

func makeShape(){
    let boundingView = UIView()
    self.view.addSubview(boundingView)
    boundingView.translatesAutoresizingMaskIntoConstraints = false
    boundingView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 0).isActive = true
    boundingView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: self.view.safeAreaInsets.top + 20).isActive = true
    boundingView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    boundingView.heightAnchor.constraint(equalToConstant: 80).isActive = true
    self.view.layoutIfNeeded()

    let redShape = UIBezierPath()
    redShape.move(to: CGPoint.init(x: boundingView.frame.minX, y: boundingView.frame.minY))
    redShape.addLine(to: CGPoint.init(x: boundingView.frame.maxX, y: boundingView.frame.minY))
    redShape.addCurve(to: CGPoint.init(x: boundingView.frame.maxX, y: boundingView.frame.maxY), controlPoint1: CGPoint.init(x: boundingView.frame.maxX - 20, y: boundingView.frame.midY - 20), controlPoint2: CGPoint.init(x: boundingView.frame.maxX - 20, y: boundingView.frame.midY + 20))
    redShape.addLine(to: CGPoint.init(x: boundingView.frame.minX, y: boundingView.frame.maxY))
    redShape.close()

    let fillColor = UIColor.init(red: 1, green: 0, blue: 0, alpha: 1)
    fillColor.setFill()
    redShape.fill()
    let shapeLayer = CAShapeLayer()
    shapeLayer.frame = boundingView.bounds
    shapeLayer.path = redShape.cgPath
    shapeLayer.fillColor = fillColor.cgColor
    boundingView.layer.addSublayer(shapeLayer)
}

在上面的代码中制作您喜欢的自动布局。但要注意形状是如何绘制的。希望能帮助到你。 输出: enter image description here

编辑:我相信向UILabel添加子图层将完全隐藏UILabel的文本。因此,我建议您完全按照上面的代码,并将UILabel作为子视图添加到boundingView。