Ios 限制多个文本字段的长度

Ios 限制多个文本字段的长度,ios,swift,swift3,uitextfield,Ios,Swift,Swift3,Uitextfield,我在一个视图控制器中有多个文本字段,并使用以下函数限制字符数: func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return textView.text.characters.count + (text.characters.count - range.length) <= 300 } func t

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

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

返回textView.text.characters.count+(text.characters.count-range.length)对于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
}
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
}
func textView(textView:UITextView,shouldChangeTextIn范围:NSRange,replacementText:String)->Bool
{
如果textView==您的textViewName
{
让str=(NSString(string:textView.text!)).replacingCharacters(in:range,with:text)
如果str.characters.count Bool
{
如果textField==您的textfieldname{
让str=(NSString(string:textField.text!)).replacingCharacters(in:range,with:string)

如果str.characters.count为这些文本字段使用标记,如果您能详细说明如何操作,那将是非常好的。您是否将这些文本字段连接到IBOutlet?是的,谢谢这一点,我实际上需要为文本字段使用不同的方法。首先,您需要一个函数来正确计算输入的字符。例如,如果您的输入是“hello”,characters.count可以完成这项工作,但是一些表情符号会为一个表情符号提供2-3个字符的计数。一旦你有了这个功能,然后按照其他人的建议使用标记。