Search code examples
swiftxcodecocoanstextfield

How to set NSTextField top-left origin?


enter image description hereSwift 4.1, Xcode 9.3, cocoa App

How to set NSTextField top left origin so it will always show up as top left regardless of how people zoom in the view?

    @IBOutlet weak var inputFromTextField: NSTextField!
    @IBAction func buttonMain(_ sender: NSButton) {
    let labelMain = NSTextField(frame: CGRect(x: Int(view.frame.origin.x) + 10, y: Int(view.frame.origin.y), width: 100, height: 100))
    labelMain.textColor = NSColor.white
    labelMain.drawsBackground = true
    labelMain.backgroundColor = NSColor.orange
    self.view.addSubview(labelMain)
}

This show up as left-bottom instead of left-top. Most of the answer show up is for iOS not cocoa app.


Solution

  • You need to add constraints. Programmatically, there are three methods:

    • create constraint objects (the hard way)
    • use the visual format language (much easier, compatible with all versions)
    • use guides (even easier, introduced in macOS 10.11)

    I'd give examples, but Apple already has a concise description of all three, with examples, in the Programmatically Creating Constraints section of Auto Layout Guide.