2017-07-03 3 views
0

私のアプリでは、一部のtextViewのテキストの制限があります。たとえば、In descriptionではテキストの制限が10000です。textViewに10000文字以上の文字が含まれている場合、キーボードのバックスペースキーを有効にしてキーボードの他のすべてのキーを無効にする必要があります。 textfieldShouldChangeでiOS Swiftキーボードのバックスペースキーのみ有効

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText string: String) -> Bool { 
    if(textView == DescriptionText) 
    { 
     if range.length + range.location > (self.DescriptionText.text?.characters.count)! 
     { 
      return false 
     } 
     else if range.location == 0 && string == " " 
     { 
      return false 
     } 
     let NewLength = (self.DescriptionText.text?.characters.count)! - range.length 
     return NewLength <= 9999 
     } 
     else 
     { 
      if range.location == 0 && string == " " 
      { 
       return false 
      } 
      return true 
     } 
    } 
+0

他のすべてのキーを無効にするのではなく、入力を正しく防止できますか? –

+0

NewLength計算が間違っています。 – YaBoiSandeep

+0

これをチェックしてくださいhttps://stackoverflow.com/a/32935626/5523205 – Shahrukh

答えて

1

次の行を追加します:ここに私の試したコードがある

if(range.length + range.location > textField.text.length) 
    { 
     return NO; 
    } 

    NSUInteger newLength = [textField.text length] + [string length] - range.length; 

    return newLength <= 10000; 
-1

私はあなたが正確に何をしたいよく分からないが、あなたはラインの下に使用してのTextView以上10000個の文字を入力するユーザーを防ぐことができます。

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText string: String) -> Bool { 

    let textString = (textView.text! as NSString).replacingCharacters(in: range, with: string) 

    if textView == self.DescriptionText && string.characters.count > 0 { 
     return textString.characters.count <= 10000 
    } 

    return true 
} 
+0

@ down-votersあなたがダウン投票のために何かを説明するなら、間違っていると自分自身を訂正します。 –

関連する問題