Prevent selecting all tokens in NSTokenField

一曲冷凌霜 提交于 2019-11-28 08:50:29

An NSTokenField is a subclass of NSTextField. There's no easy, direct way to directly manipulate the selection of these classes (aside from -selectText:, which selects all).

To do this when it becomes the first responder, you'll need to subclass NSTokenField (remember to set the class of the field in your XIB to that of your custom subclass) and override -becomeFirstResponder like so:

- (BOOL)becomeFirstResponder
{
    if ([super becomeFirstResponder])
    {
        // If super became first responder, we can get the
        // field editor and manipulate its selection directly
        NSText * fieldEditor = [[self window] fieldEditor:YES forObject:self];
        [fieldEditor setSelectedRange:NSMakeRange([[fieldEditor string] length], 0)];
        return YES;
    }
    return NO;
}

This code first looks to see if super answers "yes" (and becomes the first responder). If it does, we know it will have a field editor (an NSText instance), whose selection we can directly manipulate. So we get its field editor and set its selected range (I put the insertion point at the end with a { lastchar, nolength } range).

To do this when the field is done editing (return, tabbing out, etc.), override -textDidEndEditing: like this:

- (void)textDidEndEditing:(NSNotification *)aNotification
{
    [super textDidEndEditing:aNotification];
    NSText * fieldEditor = [[self window] fieldEditor:YES forObject:self];
    [fieldEditor setSelectedRange:NSMakeRange([[fieldEditor string] length], 0)];
}

In this case, when the user ends editing, this method lets super do its thing, then it looks to see if it's still the first responder. If it is, it does the same as above: puts the insertion carat at the end of the field.

Note, this behavior is not standard and is unexpected. Use sparingly.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!