防止在NSTokenField中选择所有令牌 [英] Prevent selecting all tokens in NSTokenField

查看:524
本文介绍了防止在NSTokenField中选择所有令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法防止NSTokenField在按下ENTER键时或在第一个响应者使用TAB键时选择所有内容?

Is there any way to prevent the NSTokenField to select everything when pressing the ENTER key or when making to the first responder maybe using the TAB key?

推荐答案

NSTokenField是NSTextField的子类。没有简单,直接的方法来直接操作这些类的选择(除了-selectText :,它选择所有)。

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).

当它成为第一个响应,您需要将NSTokenField(记住将XIB中的字段的类设置为自定义子类的类)并覆盖-becomeFirstResponder,如下所示:

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;
}

这段代码首先查看super是否回答yes第一响应者)。如果是,我们知道它将有一个字段编辑器(NSText实例),其选择可以 可以直接操作。所以我们得到它的字段编辑器并设置它的选择范围(我把插入点在一个{lastchar,nolength}范围)。

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).

字段完成编辑(返回,制表等),覆盖-textDidEndEditing:像这样:

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.

这篇关于防止在NSTokenField中选择所有令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆