簡體   English   中英

如何限制文本長度以適合動態創建的UITextField的寬度

[英]How to limit text length to fit width of dynamically created UITextField

我已經動態創建了具有不同寬度和字體大小的UITextFields 我知道如何限制UITextField長度,但是我只能使用固定的字符數來做到這一點。 我需要動態限制字符數以適合某些UITextFields 我想每次鍵入新字符時,都應該使用CGSize並獲取特定字體大小的文本長度,然后將其與UITextField寬度進行比較,並在超過UITextField寬度時限制字符數。 不幸的是,我不確定如何啟動它。 有人知道有什么代碼片段可以幫助我嗎?

您可以從以下代碼開始:

- (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;
}

暫無
暫無

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

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