设置 UITextField 最大长度以匹配屏幕宽度



嘿,我被这个难倒了。我想知道是否有办法设置UITextField的最大长度以匹配屏幕的宽度?

您可以通过四个步骤完成:

  1. 设置UITextField的委托
  2. 获取新字符串,并计算其宽度
  3. 检查字符串的宽度是否超出屏幕宽度
  4. 是否允许用户在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;
  }

最新更新