[英]How to Resize UITextField Placeholder Text to Fit UITextField width?
[英]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.