2016-10-03 103 views
0
override func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { 

     label.text = textView.text 
     return true; 
} 

有了這段代碼,我好像是一個背後的角色。在UITextView中輸入時更新UILabel

回答

3

shouldChangeTextInRange將被稱爲之前文本字段的文本值被更改。

嘗試把你的代碼,而不是textViewDidChange

func textViewDidChange(textView: UITextView) { 
    label.text = textView.text 
} 
1

您正在設置上一個textView的文本。嘗試:

override func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { 

     label.text = text 
     return true; 
} 

因爲在傳播textView的新文本之前調用此方法。

-1

您可以使用NSStringreplacingOccurrences(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 
}