Add a text above the triangle CAShapeLayer

To add a label below the triangle you just need to create it at zero origin with zero size, choose the font size, set the text alignment to center and call sizeToFit. Then all you need to do is set the center of the label at the same point you have passed to the drawTriangle method but adding half of the label’s height to the y value. To add it above the triangle you would need to subtract. half of the label’s height and the size of the triangle.

let x = view.frame.minX + 45
let y: CGFloat = 40
drawTriangle(size: 10, x: x, y: y, up: false)
let label = UILabel(frame: .init(origin: .zero, size: .zero))
label.font = .systemFont(ofSize: 10)
label.textColor = .white
label.text = "StackOverFlow"
label.backgroundColor = .red
label.textAlignment = .center
label.sizeToFit()
let labelHalfHeight = label.frame.height/2
label.center = .init(x: x, y: y + labelHalfHeight)
view.backgroundColor = .blue
view.addSubview(label)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top