How do I place NSTextField at an x, y, point?

This seems like a simple question for this group, but I haven’t been able to find the answer via other searches.

Using Swift and a macOS application, I created a view and a class called Draw1 that inherits from NSView

It begins with the statement,

class Draw1: NSView {…

In Draw1 I am using NSBezierPath(), move(…), line(…) and stroke(…) to add lines in specific locations.

Now, I need to add some text at specific x and y points in the view.

I started with..

let S1 = NSTextField()
S1.stringValue = "ABC"
S1.textColor = .black
S1.display()

These statements compile without errors.

I need something that does the same thing for the NSTextField as the move and line and stroke statements do for the lines.

How can I place S1 at a specific x,y location in the view?

.. does this existing extension to NSString do what you want (it's not a NSTextField, but do you care)?

extension NSString {
    @available(macOS 10.0, *)
    open func draw(at point: NSPoint, withAttributes attrs: [NSAttributedString.Key : Any]? = nil): NSRect, withAttributes attrs: [NSAttributedString.Key : Any]? = nil)
}

Your text color (font, etc) would be set via the withAttributes parameter, so:

NSString("ABC").draw(at: CGPoint(x: . . , y: . .),
      withAttributes: [ NSAttributedString.Key.foregroundColor: Color.black ])

[ this was extracted from some old code .. there may be prettier equivalent now ]

1 Like

Thank you !!!

I appreciate the assistance from Gavin_Eadie. He pointed out that, what he posted, was old code. Fortunately, because of those comments, and that code, I was able to find code that works for me in macOS Swift 5. This ability to place text at a specific point of a view is very important for my project that builds geometric shapes, with labels, based on an equation.

In the interest of leaving this with a complete record, here are four examples of statements that worked in macOS Swift 5.

let S1: String = "ABC"

NSString(string: S1).draw(at: CGPoint(x: 100, y: 50))

let I1: Int = 42
let S2 = String(I1)
NSString(string: S2).draw(at: CGPoint(x: 200, y: 50))

NSString(string: S2).draw(at: CGPoint(x: 300, y: 50), withAttributes:[NSAttributedString.Key .foregroundColor: NSColor.red ])

NSString(string: S2).draw(at: CGPoint(x: 400, y: 50), withAttributes:[NSAttributedString.Key .foregroundColor: NSColor.black, .font: NSFont(name: "Helvetica", size: 24)! ])