dobry
dobry

Reputation: 141

NSTextField gets focus but no text input cursor is visible

NSTextField is not working as expected in my case. What I got is:

I'm doing the steps:

BUT, there is no cursor blinking. I can edit, and cursor shows when I start typing, so I presume, the text field has focus. I need to have cursor blinking there immediately after the view expands.

To animate this "Edit Subject" view's height I use NSAnimationContext runAnimationGroup and in completion handler I'm calling makeFirstResponder on NSTextField's window with NSTextField as first responder.

I tried different combination of running makeFirstResponder: before starting animation, in animation's completion handler, tried different variations of performSelector: call on main thread, used dispatch_async, dispatch_after, even performClick: (but this shrink-animates container view to 0, because any click outside closes it). The effect is always the same: there is focus on NSTextField - I can type in this text field, but initially there is no keyboard input cursor.

When the editing is done, the makeFirstResponder on NSText which is chat's text input window cursor shows there properly.

What am I missing there? Why text field gets focus without cursor? What can prevent NSTextField that is made first responder not to show cursor? I'm almost completely sure I'm not making any other control first responder afterwards anywhere in the app. Please help.

Upvotes: 3

Views: 2029

Answers (3)

isaced
isaced

Reputation: 1804

The problem I'm having is that when switching focus between two NSTextViews and their text is empty, the cursor is always invisible (macOS 13.4.1).

Inspired by @dobry answer, this can be solved by subclassing NSTextView.

class MyNSTextView: NSTextView {
    override func becomeFirstResponder() -> Bool {
        let result = super.becomeFirstResponder()
        if result {
            ensureCursorBlink()
        }
        return result
    }

    func ensureCursorBlink() {
        if string.isEmpty {
            string = ""
        }
    }
}

Upvotes: 2

ilsinszkibal
ilsinszkibal

Reputation: 23

After days of trying this works for me:

[textField selectText:nil];

See this thread: http://cocoadev.github.io/MakingNSTextFieldActive/

Upvotes: 1

dobry
dobry

Reputation: 141

After hours of experiments and internet browsing in search for solution I found this extremely useful hack:

https://gist.github.com/Kapeli/7abd83d966957c17a827

- (void)ensureCursorBlink 
{
    if(isYosemite && !self.stringValue.length)
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(!self.stringValue.length)
        {
            [self setStringValue:@" "];
            [self setStringValue:@""];
        }
        });
   }
}

and call it after makeFirstResponder:. Actually, it worked for me even without dispatch_after.

Upvotes: 4

Related Questions