5

I have set an NSMenuItem's view to a custom view, which contains a textfield. When I run the program, everything works as expected. NSTextField is part of the NSStatusItem and accepts focus and I can type things in it.

After closing the menu and going to a different window, When I click the menu and try to bring the focus back to the NSTextField, it becomes readonly.

enter image description here

Code:

import Cocoa
import CoreLocation

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate, NSTextFieldDelegate {

    @IBOutlet weak var window: NSWindow!
    var statusItem: NSStatusItem
    @IBOutlet weak var statusMenu: NSMenu!
    @IBOutlet weak var firstMenuItem: NSMenuItem!
    @IBOutlet weak var textField: NSTextField!

    override func awakeFromNib() {
        statusItem.menu  = statusMenu
    }
    override init() {
        statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength)
        super.init()
    }

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        if let button = statusItem.button {
            button.image = NSImage(named:"StatusBarButtonImage")
        }
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }
 }

Is there a way to bring the focus back to NSTextField?

I tried becomeFirstResponder, canBecomeKeyView but they do not seem to be working in this case.

felix
  • 11,304
  • 13
  • 69
  • 95
  • Show the code you're using to allow input into the `NSTextField`. – l'L'l May 25 '16 at 00:29
  • Just updated with the code sample. It's really boilerplate stuff. – felix May 25 '16 at 00:44
  • I am not using any code which allows input into NSTextField. It's just an default NSTextField. It is editable initially but then becomes readonly after losing focus. – felix May 25 '16 at 00:47
  • 1
    I have this issue at this moment. Actually the application is losing the state of "activate". I will post the answer if I find a good way to activate it back without breaking the user experience. – Gaston Siffert Jul 03 '16 at 15:28
  • Gaston, I saw a lot of references to this approach(http://mattgemmell.com/maattachedwindow-nswindow-subclass/) I did not have a chance to try it. – felix Jul 25 '16 at 17:01
  • @felix did you find solution to this? I have the same problem. – sftsz Jan 11 '17 at 08:20
  • Gaston Siffert's comment should be accepted as answer. Cause your app is NOT active now. – Jiulong Zhao Apr 19 '17 at 19:39

0 Answers0