shouldChangeCharactersInRange与特殊分离

时间:2013-08-30 09:20:07

标签: iphone

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

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

示例: XXNL XNLX XLMD XMLD XX

我知道我必须使用这种方法...

UITextField

但不知道如何处理这种方法。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

在该委托方法中,您应该构建textField包含的字符串。 然后,您可以检查模5的字符串的长度是否为4(因此在4个字符之后它会触发,在9个字符之后(4 + 1空格+其他4个字符)再次触发,依此类推。如果检查触发,则为在textField文本上添加一个空格@“”。

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

另一种方法是在同一方法中修剪字符串(删除所有空格),然后每4个字符再次添加空格

答案 1 :(得分:-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;