2013-08-30 26 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個字符重新添加空格