Если вам, например, необходимо создать подкласс UILabel
, а затем добавить немного CALayer
, которое охватывает текст, рекомендуется добавить CATextLayer
к вашему CALayer
, вот быстрый пример:
@IBDesignable class BWRoundedLabel: UILabel {
override var text: String? {
didSet {
updateView()
}
}
@IBInspectable override var shadowColor: UIColor? {
didSet {
updateView()
}
}
private func updateView() {
let width = bounds.size.width - 1
let height = bounds.size.height - 1
let shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: CGRectMake(0, 0, width, height), cornerRadius: width/2).CGPath
shadowLayer.fillColor = UIColor.yellowOrange().CGColor
shadowLayer.shadowColor = shadowColor?.CGColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 0, height: 1.0)
shadowLayer.shadowOpacity = 1
shadowLayer.shadowRadius = 0
let textLayer = CATextLayer()
textLayer.foregroundColor = UIColor.whiteColor().CGColor
textLayer.string = text
textLayer.fontSize = font.pointSize
textLayer.font = "Calibri-Bold"
textLayer.alignmentMode = kCAAlignmentCenter
textLayer.frame = CGRectMake(0, (height - 16)/2, width, 16)
if let sublayers = layer.sublayers {
for sublayer in sublayers {
sublayer.removeFromSuperlayer()
}
}
layer.insertSublayer(shadowLayer, atIndex: 0)
layer.insertSublayer(textLayer, atIndex: 1)
}
}