Jenny Makula Jenny Makula - 1 month ago 19
Swift Question

Drawing text at a CGPoint

I created a UIView with a custom triangle using UIBezierPath and draw(_ rect: CGRect).

I want to add text labels to the triangle for each of its three points at their CGpoints.

How do I do that?

class TriangleView: UIView {

override func draw(_ rect: CGRect)
{
color.set()
pathForTriangle().stroke()
}
}





Solution based on Mathias Quintero's answer:

override func layoutSubviews()
{
calculatePoints()
let label1 = UILabel(frame: CGRect(origin: point1, size: CGSize(width: 300, height: 20)))
addSubview(label1)
label1.text = "test"
}

Answer

Adding TextLabels should not happen as part of the drawing inside of the view. Instead what you should do is add the labels as subviews of your view.

addSubview(:) should do the trick.

When it comes to placing the labels correctly you'll have to think of either adding some constraints or manually changing the frame of the labels to be at the correct position.

You can and should do all of this in viewWillLayoutSubviews() or layoutSubviews() in Swift3

Comments