我动态创建了具有不同宽度和字体大小的 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;
}
关于ios - 如何限制文本长度以适应动态创建的 UITextField 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16216592/