Search code examples
swiftmacosnstextfield

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


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.


Solution

  • 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)
    }