ios - 如何根据 TextField 的可见大小限制 UITextField 的输入文本量?

标签 ios objective-c uitextfield uikit

我有一个表单应用程序,其中包含许多不同大小的 UITextFields。我想将输入文本量限制为文本字段在截断字符串之前可以容纳的文本量。关于堆栈溢出的所有其他答案似乎都知道事先限制字符数(例如,我想限制为 40 个字符),但我需要知道如何根据文本字段的大小来限制它(这与文本字段不同)到文本字段)。

有办法做到这一点吗?

谢谢

最佳答案

由于字符串的长度取决于字符,因此在知道字符之前您无法确定最大字符数,因此我建议您测试每个字符输入是否适合文本字段,例如:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    // Combine the new text with the old
    NSString *combinedText = [textField.text stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%@", string]];

    // See if the width of the combined text + the text field's
    // left layout margin + the text field's right layout margin
    // is greater than or equal to the width of the textField
    // (I've multiplied the right margin by 2 to prevent the cursor
    // from shifting the field one extra character when the text field
    // if full)
    CGFloat textWidth =  [combinedText sizeWithAttributes:@{NSFontAttributeName: textField.font}].width + textField.layoutMargins.left + textField.layoutMargins.right * 2;
    CGFloat textFieldWidth = textField.frame.size.width;

    // If the text + margins is as wide or wider than the text field
    // don't add the new character, i.e. return NO. Else add the
    // character by returning YES.
    if (textWidth >= textFieldWidth) {
        return NO;
    } else {
        return YES;
    }
}

关于ios - 如何根据 TextField 的可见大小限制 UITextField 的输入文本量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449895/

相关文章:

objective-c - iOS:如何将 "cartoon"风格的动画(电影)添加到幻灯片中?

ios - 如何从 Swift 3 中的父 View Controller 中删除 ChildViewController

ios - 在 const NSString *const[] 中查找 NSString

ios - 如何从右到左而不是从左到右显示 UICollectionView 的单元格?

objective-c - 如何在 objective-c 中声明全局变量

ios - Coredata 和关系的自动排序

ios - OpenWeatherMap 中不同大小的天气图标

ios - iOS : UITextField vs UITextView 中的多行用户输入

ios - 在键盘上方添加 UITextField

swift - UITextField 在 Swift 中设置最大字符长度