【问题标题】:Limit length of several text fields限制几个文本字段的长度
【发布时间】:2017-12-08 12:51:37
【问题描述】:

我在一个视图控制器中有多个文本字段,我正在使用以下函数来限制字符数:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    return textView.text.characters.count + (text.characters.count - range.length) <= 300
}

如何更改不同文本字段的最大字符数?我需要另一个文本字段的下限。

【问题讨论】:

  • 为这些文本字段使用标签
  • 如果您能详细说明如何做到这一点,那就太好了
  • 您是否将这些文本字段连接到 IBOutlet?
  • 是的,谢谢,我实际上需要一种不同的 TextField 方法。
  • 首先,您需要一个函数来正确计算输入的字符数。即,如果您的输入是“你好”,characters.count 将完成这项工作,但一些表情符号会给您一个表情符号 2-3 个字符的计数。拥有该功能后,请按照其他人的建议使用标签。

标签: ios swift swift3 uitextfield


【解决方案1】:

对于 TextView,您需要使用以下 TextView 委托方法

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
     if textView == yourTextViewName
     {
         let str = (NSString(string: textView.text!)).replacingCharacters(in: range, with: text)
         if str.characters.count <= 300 {
             return true
         }
         textView.text = str.substring(to: str.index(str.startIndex, offsetBy: 300))
         return false
     } 
     return true
}

对于 TextField 你必须使用下面的委托方法

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    if textField == yourTextFieldName {
        let str = (NSString(string: textField.text!)).replacingCharacters(in: range, with: string)
        if str.characters.count <= 300 {
            return true
        }
        textField.text = str.substring(to: str.index(str.startIndex, offsetBy: 300))
        return false
    }
    return true
}

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2020-12-11
    • 2016-03-27
    • 2015-01-06
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多