override func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
label.text = textView.text
return true;
}
有了這段代碼,我好像是一個背後的角色。在UITextView中輸入時更新UILabel
override func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
label.text = textView.text
return true;
}
有了這段代碼,我好像是一個背後的角色。在UITextView中輸入時更新UILabel
shouldChangeTextInRange
將被稱爲之前文本字段的文本值被更改。
嘗試把你的代碼,而不是textViewDidChange:
func textViewDidChange(textView: UITextView) {
label.text = textView.text
}
您正在設置上一個textView的文本。嘗試:
override func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
label.text = text
return true;
}
因爲在傳播textView的新文本之前調用此方法。
您可以使用NSString
replacingOccurrences(of:with:)
得到鍵入文本,這樣
Swift2
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let originText = textView.text as NSString
let replacingText = originText.stringByReplacingCharactersInRange(range, withString: text)
label.text = replacingText
return true
}
Swift3
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let originText = textView.text as NSString
let replacingText = originText.replacingCharacters(in: range, with: text)
label.text = replacingText
return true
}