簡體   English   中英

UITextField - 在鍵入時輸入第一個字符后添加一個字符

[英]UITextField - Add a character/s after 1st character is entered while typing

我有一個UITextField,它將包含高度值。 我想在用戶輸入UITextField時格式化字段的值。 例如,如果我想輸入值為“5英尺10”,則流程將為:

1. Enter 5
2. " ft " is appended immediately after I type 5 with leading & trailing space.

我的代碼看起來像這樣:

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

if ( [string isEqualToString:@""] ) return YES;

// currHeight Formatting
if ( textField == currHeight )  { 
   if (currHeight.text.length == 1) {   
        currHeight.text = [NSString stringWithFormat:@"%@ ft ", currHeight.text];    
        }
}
return YES; 
}

我被困在我輸入的地步5沒有任何反應。 我必須點擊任何按鈕才能追加“ft”。

我可以不點擊任何東西嗎?

-shouldChangeCharactersInRange在更改文本字段之前被調用,因此長度仍為0(請參閱使用`textField:shouldChangeCharactersInRange:`,如何獲取包含當前類型字符的文本? )。 試試這個:

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range
replacementString: (NSString*) string {
    if (textField == currHeight) {
        NSString *text = [textField.text stringByReplacingCharactersInRange:range
        withString: string];
        if (text.length == 1) { //or probably better, check if int
            textField.text = [NSString stringWithFormat: @"%@ ft ", text];
            return NO;
        }
    }
    return YES;
}  

調用此函數時,currHeight.text仍然具有長度0.返回YES后,文本僅更新為5。

做你想做的事情的方法是測試currHeight.text.length是否為0,string.length是1,字符串的第一個字符是數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM