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

查看:20
本文介绍了防止选择 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 是否回答是"(并成为第一响应者).如果是,我们知道它将有一个字段编辑器(一个 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)];
}

在这种情况下,当用户结束编辑时,这个方法让 super 做它的事情,然后看看它是否仍然是第一响应者.如果是,则执行与上述相同的操作:将插入克拉放在字段的末尾.

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天全站免登陆