2013-04-25 86 views
2

我已經動態創建了具有不同寬度和字體大小的UITextFields。我知道如何限制UITextField中的文字長度,但是我只能使用固定的字符數做到這一點。我需要的是動態限制字符數以適合某些UITextFields。我想每次輸入新字符時,我都應該使用CGSize,並且獲得特定字體大小的文本長度,而不是將其與UITextField寬度進行比較,並且如果超過了UITextField寬度,則限制字符數。不幸的是我不知道如何啓動它。有誰知道可以幫助我的任何代碼片段?如何限制文本長度以適應動態創建的UITextField的寬度

回答

6

您可以從這些代碼開始:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    NSString *text = textField.text; 
    text = [text stringByReplacingCharactersInRange:range withString:string]; 
    CGSize textSize = [text sizeWithFont:textField.font]; 

    return (textSize.width < textField.bounds.size.width) ? YES : NO; 
} 

IOS 7後,它改變sizeWithFont到sizeWithAttributes。

下面是修改代碼:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    NSString *text = textField.text; 
    text = [text stringByReplacingCharactersInRange:range withString:string]; 
    CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:textField.font}]; 

    return (textSize.width < textField.bounds.size.width) ? YES : NO; 
} 
+0

輝煌!它像我想要的那樣完美。 – Guferos 2013-04-26 11:39:46

+0

我也發現這個作品,只是從文本字段中拉出默認屬性:CGSize textSize = [text sizeWithAttributes:[textfield defaultTextAttributes]]; – chrisallick 2014-11-02 01:08:16

相關問題