2017-07-03 96 views
0

在我的應用程序中,我對文本限制爲textView。例如,在description我有文本限制10000.當textView包含超過10000個字符我只需要在鍵盤中啓用退格鍵,並需要禁用鍵盤中的所有其他鍵,是否有可能。這是我試過的代碼:iOS Swift在鍵盤上只啓用Backspace鍵

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

在textfieldShouldChange添加以下內容:

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-vot如果你解釋一些投下來的東西,我會糾正自己,如果它是錯誤的。 –