嘿,我被这个难倒了。我想知道是否有办法设置UITextField
的最大长度以匹配屏幕的宽度?
您可以通过四个步骤完成:
- 设置
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 sizeWithAttributes:@{NSFontAttributeName:textField.font}];
return textSize.width < textField.bounds.size.width;
}