Cursor doesn't update in NSTextField as it autoresizes when resizing the enclosing NSWindow

190 views Asked by At

I have an NSTextField that autoresizes. Its text is centered.

When I start typing in the field and then resize the enclosing NSWindow, the cursor stays where it's at rather than repositioning to the appropriate place :

cursor is way on the left while it should be placed at the end of the text

I've also made an XCode project demonstrating this problem : https://www.dropbox.com/sh/cohhmslyl9ti43b/AAC6ULteopsQCMDsEArJU15Ta?dl=0

Does anyone know what is happening here?

1

There are 1 answers

3
A O On BEST ANSWER

Interesting question, I've never applied auto-layout to a text field so I was curious myself.

My solution was to listen for the NSWindowDelegate method, -windowDidResize. Upon that, I would check to see if the text field was the first responder. If it was, I set it to be first responder again, which resets the cursor in the correct location.

Code:

   NSResponder *firstResponder = [[NSApp keyWindow] firstResponder];
   if ([firstResponder isKindOfClass:[NSText class]] && (NSTextField*)[(NSText *)firstResponder delegate] == self.centeredText) {
      [self.centeredText becomeFirstResponder];
   }

I reuploaded the project so you could look too: https://www.dropbox.com/s/lhsspi5gasbwq8j/CursorDoesNotUpdate%202.zip?dl=0