您可以從這些代碼開始:
- (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;
}
輝煌!它像我想要的那樣完美。 – Guferos 2013-04-26 11:39:46
我也發現這個作品,只是從文本字段中拉出默認屬性:CGSize textSize = [text sizeWithAttributes:[textfield defaultTextAttributes]]; – chrisallick 2014-11-02 01:08:16