override func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
label.text = textView.text
return true;
}
使用此代码,我似乎是一个背后的角色。
答案 0 :(得分:3)
shouldChangeTextInRange
将被称为之前文本字段的文本值已更改。
尝试将代码改为textViewDidChange:
func textViewDidChange(textView: UITextView) {
label.text = textView.text
}
答案 1 :(得分:1)
您正在设置之前的textView文本。尝试:
override func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
label.text = text
return true;
}
因为在传播textView的新文本之前调用此方法。
答案 2 :(得分:-1)
您可以使用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
}