I am using the following code to deselect an NSTextView
, as suggested here. Unfortunately, nothing at all happens. I have tried what I know to debug it, but everything seems to be working correctly, but it doesn't affect the NSTextView
.
The code:
// Sets the scrolling bounds and behavior. This might be useful, but I don't know
[[textView textContainer] setContainerSize:NSMakeSize(FLT_MAX, FLT_MAX)];
[[textView textContainer] setWidthTracksTextView:FALSE];
// The code for deselecting, beginning by making sure it is actually selected (for testing only, as strange as it is)
[textView setSelectable:TRUE];
[textView setDelegate:self];
[_window makeFirstResponder:textView];
NSText *fieldEditor = [_window fieldEditor:TRUE forObject:textView];
[fieldEditor setSelectedRange:NSMakeRange([[fieldEditor string] length],0)];
[fieldEditor setNeedsDisplay:YES];
Any ideas about why this doesn't work? I am sure my outlets are set properly because I can manipulate other things, such as it's string value.
I'm not sure NSTextViews use the field editor, have you tried calling the method on the text view directly?
[textView setSelectedRange:NSMakeRange(textView.string.length, 0)];
The range location can be adjusted to move the cursor to the start or end, for example. You may also want to check to make sure something is actually selected before calling this method.
EDIT:
From your comment it sounds like you just want it to resign first responder. You can do that manually by calling [textView.window makeFirstResponder:nil];
This almost worked for me;
[textView.window makeFirstResponder:nil];
However, I had trouble setting the first responder to nil. If I set it to any other view it seems to do as you want.
[textView.window makeFirstResponder:[textView superview]];
Tested in 10.7 Lion.
I've using this approach and it works perfectly:
[textView setSelectedRange:NSMakeRange(0, 0)];
As suggested earlier setSelectedRange:
will do the trick BUT!
If your goal is to completely remove the selection and the cursor too, f.e. if you subclass an NSTextView
to support similar behavior like NSTextEdit
has in case of firstResponder
status change you should write:
- (BOOL)resignFirstResponder
{
// Invalid range location will remove cursor too
[self setSelectedRange:NSMakeRange(NSUIntegerMax, 0)];
return YES;
}
//------------------------------------------------------------------------------
- (BOOL)becomeFirstResponder
{
[self setSelectedRange:NSMakeRange(0, self.string.length)];
return YES;
}
//------------------------------------------------------------------------------
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With