2016-10-13 7 views
0

文字の入力が100個に制限されたUITextViewがあります。 textView:shouldChangeTextInRange:replacementText:メソッドを使用して文字入力を追跡することができます。 私のケースでは、キーボードを何も中断することなく、ボタンクリックで文字をテキストビューに入力するだけのチャンスがあります。そのような場合は、上記のデリゲートメソッドが呼び出されないので、テキストビューの文字数を追跡できず、100文字を超えることができます。 このようなケースはどのように処理する必要がありますか?助けてください。キーボードで入力していないときにUITextviewで文字の変更を追跡する

答えて

1

あなたはスウィフト3コードの下に試すことができます: -

@IBAction func buttonClicked(sender: AnyObject) { 
      self.textView.text = self.textView.text + "AA" //suppose you are trying to append "AA" on button click which would call the below delegate automatically 
     } 

//Below delegate of UITextViewDelegate will be called from keyboard as well as in button click 
func textViewDidChangeSelection(_ textView: UITextView) { 
     if textView.text.characters.count > 100 { 

      let tempStr = textView.text 
      let index = tempStr?.index((tempStr?.endIndex)!, offsetBy: 100 - (tempStr?.characters.count)!) 
      textView.text = tempStr?.substring(to: index!) 
     } 
    } 
0

私の知る限り、テキストフィールドに既存のテキストを追加するカスタムボタンがあります。あなたが検証メソッド

func validateString(string: String) -> Bool { 
    return string.characters.count <= 100 
} 

を実装し、shouldChangeCharactersInRange方法やボタンのコールバックにそれを使用することができます。この場合

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { 
    let currentString: NSString = (textField.text ?? "") as NSString 
    let newString = currentString.replacingCharacters(in: range, with: string) 
    return validateString(string: newString) 
} 

@IBAction func buttonPressed() { 
    let newString = textField.text + "a" //replace this line with your updated string 
    if validateString(string: newString) { 
     textField.text = newString 
    } 
} 
関連する問題