2013-08-30 27 views
1

我正在尝试创建特殊的UITextField,其中文本将在一定数量的字符后分开。我知道-shouldChangeCharactersInRange代表UITextField可以使用。shouldChangeCharactersInRange与特殊分隔

现在,我需要一些更复杂的分隔,同时在UITextField中输入文本。我需要在每4个字符后用空格分隔空格。最后2个字符也应该与其余的空格分开。

例子: XXNL XNLX XLMD XMLD XX

我知道我必须要使用此方法...

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 

但不知道做什么用这种方法做的。谁能帮我 ?

+0

尝试保存以前的字符并比较当前字符和先前的字符是空格然后返回否则不允许。空间af一个角色是允许的,并且空间之后的空间是不允许的。 – NHS

+0

是的,我已经尝试过这一个。只有空格应该自动添加。用户必须像正常一样输入值,系统应该添加空格。 – user1713954

回答

-1
See if you want that style of text then after every 4 characters in textfield text just add one space.and if length is total characters you want then don't allow any other characters.In shouldchangecharactersinRange: you have to insert 1 space programatically 

if(textfield.text.length % 4 == 0) then 
    string = [string stringbyappendingstring:@""]; 

Do this it will fix your requirement and dont accept any characters after the length you need,like 

if(textfield.text.length == someinteger) then 
    don't accept the string just return NO; 
0

在该委托方法中,您应该构建textField包含的字符串。 然后,你可以检查模5的字符串长度是否为4(这样在4个字符之后它会被触发,并且在9个字符之后(4 + 1空格+其他4)它会再次触发,等等。你添加一个空格@”“在文本框的文本。

有这样做的问题是,如果用户移动光标,更改文本,那么一切都将丢失,

另一种方式,你可以做到这一点然后在同一方法中修剪字符串(删除所有空格),然后每4个字符重新添加空格