如何绘制自定义标签边框3边和1边

时间:2015-11-29 00:15:12

标签: swift2 xcode7

我想画一个标签(UILabel)的边框,有三个直边和一个圆角,你可以看到一个示例图片:example label

我使用X-Code 7和Swift 2.1

1 个答案:

答案 0 :(得分:0)

您可以创建形状图层并在标签中使用它。我试图接近Playground的样本:

import UIKit
import XCPlayground

let label = UILabel(frame: CGRect(x: 50, y: 170/2, width: 100, height: 30))


let rectanglePath = UIBezierPath(roundedRect: CGRectMake(1.5, 1.5, 97, 27), byRoundingCorners: [UIRectCorner.TopRight, UIRectCorner.BottomRight], cornerRadii: CGSizeMake(15, 15))
rectanglePath.closePath()
let color = [#Color(colorLiteralRed: 0.8442155122756958, green: 0.9805876612663269, blue: 0.9611368179321289, alpha: 1)#]
color.setFill()
rectanglePath.fill()
color.setStroke()
rectanglePath.lineWidth = 3
rectanglePath.stroke()

let mask = CAShapeLayer()
mask.path = rectanglePath.CGPath

label.textAlignment = .Center
label.backgroundColor = [#Color(colorLiteralRed: 0.990426778793335, green: 0.5112959146499634, blue: 0.4327127933502197, alpha: 1)#]
label.text = "Welcome...."
label.font = UIFont.systemFontOfSize(10)
label.layer.mask = mask

let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = color
view.addSubview(label)

XCPShowView("Label", view: view)