如何限制NSTokenField中的令牌数? [英] How to Limit the Number of Tokens in a NSTokenField?

查看:64
本文介绍了如何限制NSTokenField中的令牌数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSTokenField,在按Enter时在其中创建令牌。我想限制此字段中令牌的数量。举例来说,应该只允许用户一个接一个地输入2个令牌。以后,既不应该允许用户设置令牌,也不应该允许用户进一步搜索。简而言之,应在2个令牌后阻止用户。

I have a NSTokenField Where the tokens are created upon hitting enter. I would like to limit the number of tokens in this field. Say for example, User should be allowed to enter only 2 tokens one after the other. Later, neither user should be allowed to set the Token nor user should be allowed to search further. In short, User should be blocked after 2 tokens.

任何人都可以帮助我实现这一目标吗?

Could any one please help me in achieving this???

预先感谢:)

推荐答案

解决方案分为两部分:

-(NSArray *)tokenField:(NSTokenField *)tokenField shouldAddObjects:(NSArray *)tokens atIndex:(NSUInteger)index
{
    //limit the tokens
    if(self.tokensLimit)
    {
        NSArray * tokensArray = [_tokenField objectValue];

        if([tokensArray count] > 0)
        {
            if([tokens isEqualToArray:tokensArray])
            {
                return tokens;
            }
            else if([tokensArray count]>=self.tokensLimit)
            {
                return @[];
            }
            else if([tokens count]>0)
            {
                tokens = [tokens subarrayWithRange:NSMakeRange(0, MIN([tokens
                                                                       count], self.tokensLimit))];
            }
            else
                return @[];
        }
        else
        {
            tokens = [tokens subarrayWithRange:NSMakeRange(0, MIN([tokens count], self.tokensLimit))];
        }
    }

    return tokens;
}

其中tokensLimit是int> 0
代表涵盖了所有

where tokensLimit is an int > 0 the delegate covers all the cases like tokens added by copy/paste, completion list, drag&drop, manually written etc..

此其他代表介绍了用户写字符串并命中的情况,例如复制/粘贴,完成列表,拖放,手动编写等。 TAB

this other delegate cover the case where the user write a string and hit "TAB"

- (BOOL)control:(NSControl *)control isValidObject:(id)object
{
    if(self.tokensLimit)
    {
        NSArray * tokensArray = [_tokenField objectValue];
        tokensArray = [tokensArray subarrayWithRange:NSMakeRange(0, MIN([tokensArray count], self.tokensLimit))];
        [_tokenField setObjectValue:tokensArray];
    }
    return YES;
}

这篇关于如何限制NSTokenField中的令牌数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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