Swift Swift - 1 year ago 86
Swift Question

How to attach a text label to rectangle's vertex in macOS app via Swift?

I need to attach a text label to one of four vertices (CGPoints) of a rectangle. This labelled point must show x/y coordinates in macOS app.
Is there any approach like label.text found in iOS?

Answer Source

You'll need to set the frame property on an instance of a NSLabel to position (and size it).

One tricky piece is that you have to ensure the label is of large enough size as to not clip the text.

let label : NSTextField = // get a static text field from IB or previous initialization
label.stringValue = // get the label's contents
label.sizeToFit() // ensures the label's bounds do not clip the text
let point = // get the CGPoint you want this to be placed at in the Cocoa coordinate plane
label.frame = CGRect(origin: point, size: CGSize(width: label.bounds.width, height: label.bounds.height))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download