-2

How to focus on a text field when opening an application?

Swift 4, Xcode 10, macOS

ANSWER:

Thanks to the advice by @Willeke in the comments, I did it this way:

import Cocoa
import AppKit
import Foundation
let defaults = UserDefaults.standard

class ViewController: NSViewController{

    @IBOutlet weak var addDomain: NSTextField!
    @IBOutlet weak var addSiteField: NSTextField!
    @IBOutlet weak var tableView: NSTableView!
    @IBOutlet weak var removeSite: NSSegmentedControl!

    override func viewDidAppear() {
        super.viewDidAppear()
        addDomain.window?.makeFirstResponder(addDomain)

    }

Because: https://developer.apple.com/documentation/appkit/nsresponder/1526750-becomefirstresponder

Use the NSWindow makeFirstResponder(_:) method, not becomeFirstResponder() method, to make an object the first responder. Never invoke this method directly.

Marina
  • 44
  • 6
  • FYI: you can just paste a code in the post, not an image from your IDE. It's easier for you and for readers of your question. Have a nice coding :) – hamsternik Oct 19 '18 at 13:34
  • 1
    Always post code, data, logs, error message, etc as text (not images) so they are searchable, and can be copied when answering. Please [edit] your question – Ashley Mills Oct 19 '18 at 13:55
  • 3
    Don't call `becomeFirstResponder`. "Use the NSWindow makeFirstResponder: method, not this method, to make an object the first responder. Never invoke this method directly." – Willeke Oct 19 '18 at 14:49
  • @Willeke Thanks! Did as you said. Check post please. Now I did the right thing? – Marina Oct 19 '18 at 17:17

2 Answers2

1

You seem to be not over-riding the viewDidAppear that belongs to your NSViewController, but you are adding a new function on it's own.

Try using:

override func viewDidAppear() {
    // Though the default implementation does nothing as of now, 
    // it is always safe to have the call to the super function in place, 
    // in case you plan to add sub-classes in between.
    super.viewDidAppear()

    addDomain.window?.makeFirstResponder(addDomain)
}
D V
  • 348
  • 2
  • 10
-1

In your viewController in viewDidAppear

yourTextField.becomeFirstResponder()

Update:

macOS implementation requires using NSWindow makeFirstResponder!

inokey
  • 5,434
  • 4
  • 21
  • 33
  • Thanks for attention! Pls check my post. May be something wrong? – Marina Oct 19 '18 at 13:21
  • Don't call `becomeFirstResponder`. Please read the documentation. – Willeke Oct 19 '18 at 14:48
  • @Willeke as per documentation `Call this method when you want to the current object to be the first responder` – inokey Oct 19 '18 at 14:56
  • 2
    Please read the macOS version: [becomeFirstResponder](https://developer.apple.com/documentation/appkit/nsresponder/1526750-becomefirstresponder?language=occ). – Willeke Oct 19 '18 at 15:00