Guf*_*ros 2 xcode objective-c uitextfield ios ios6
我已经动态创建了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;
}
Run Code Online (Sandbox Code Playgroud)
在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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4139 次 |
| 最近记录: |