Jenny Makula Jenny Makula - 1 year ago 103
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)

Solution based on Mathias Quintero's answer:

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download