设置 UITextField 的最大字符长度 [英] Set the maximum character length of a UITextField

查看:32
本文介绍了设置 UITextField 的最大字符长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我加载 UIView 时,如何在 iPhone SDK 的 UITextField 中设置最大字符数?

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

推荐答案

虽然 UITextField 类没有 max length 属性,但通过设置文本字段的 delegate 来获得此功能相对简单 并实现以下委托方法:

While the UITextField class has no max length property, it's relatively simple to get this functionality by setting the text field's delegate and implementing the following delegate method:

目标 C

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // Prevent crashing undo bug – see note below.
    if(range.length + range.location > textField.text.length)
    {
        return NO;
    }
        
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return newLength <= 25;
}

迅捷

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    let currentCharacterCount = textField.text?.count ?? 0
    if range.length + range.location > currentCharacterCount {
        return false
    }
    let newLength = currentCharacterCount + string.count - range.length
    return newLength <= 25
}

在文本字段更改之前,UITextField 会询问代理是否应该更改指定的文本.此时文本字段没有改变,所以我们获取它的当前长度和我们插入的字符串长度(通过粘贴复制的文本或使用键盘输入单个字符)减去范围长度.如果这个值太长(本例中超过 25 个字符),返回 NO 禁止更改.

Before the text field changes, the UITextField asks the delegate if the specified text should be changed. The text field has not changed at this point, so we grab it's current length and the string length we're inserting (either through pasting copied text or typing a single character using the keyboard), minus the range length. If this value is too long (more than 25 characters in this example), return NO to prohibit the change.

在文本字段末尾输入单个字符时,range.location 将是当前字段的长度,而 range.length 将为 0,因为我们不会替换/删除任何东西.插入文本字段的中间只是意味着不同的 range.location,粘贴多个字符意味着 string 包含多个字符.

When typing in a single character at the end of a text field, the range.location will be the current field's length, and range.length will be 0 because we're not replacing/deleting anything. Inserting into the middle of a text field just means a different range.location, and pasting multiple characters just means string has more than one character in it.

删除单个字符或剪切多个字符由具有非零长度和空字符串的 range 指定.替换只是一个非空字符串的范围删除.

Deleting single characters or cutting multiple characters is specified by a range with a non-zero length, and an empty string. Replacement is just a range deletion with a non-empty string.

正如评论中提到的,UITextField 存在一个可能导致崩溃的错误.

As is mentioned in the comments, there is a bug with UITextField that can lead to a crash.

如果您粘贴到字段中,但您的验证实现阻止了粘贴,则粘贴操作仍会记录在应用程序的撤消缓冲区中.如果您随后触发撤消(通过摇动设备并确认撤消),UITextField 将尝试用空字符串替换它认为粘贴到自身的字符串.这会崩溃,因为它从未实际上将字符串粘贴到自身中.它将尝试替换不存在的字符串部分.

If you paste in to the field, but the paste is prevented by your validation implementation, the paste operation is still recorded in the application's undo buffer. If you then fire an undo (by shaking the device and confirming an Undo), the UITextField will attempt to replace the string it thinks it pasted in to itself with an empty string. This will crash because it never actually pasted the string in to itself. It will try to replace a part of the string that doesn't exist.

幸运的是,您可以保护 UITextField 不会像这样杀死自己.您只需要确保它建议替换的范围确实存在于其当前字符串中.这就是上述初始健全性检查的作用.

Fortunately you can protect the UITextField from killing itself like this. You just need to ensure that the range it proposes to replace does exist within its current string. This is what the initial sanity check above does.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let str = (textView.text + text)
        if str.characters.count <= 10 {
            return true
        }
        textView.text = str.substring(to: str.index(str.startIndex, offsetBy: 10))
        return false
    }

希望对你有帮助.

这篇关于设置 UITextField 的最大字符长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆