想在使用者在 UITextView 裡打字時即時做出反應,關鍵在於把它的 delegate 設為自己,再實作 textViewDidChange 這個方法即可。先來看看怎麼建立 UITextView 並掛上代理:
m_contentTextField = [[[UITextView alloc] init] autorelease]; m_contentTextField.frame = CGRectMake(0, 0, 320, 90) ; m_contentTextField.backgroundColor = [UIColor whiteColor] ; m_contentTextField.font = [UIFont systemFontOfSize:14]; m_contentTextField.delegate = self ; [m_contentTextField becomeFirstResponder];
接著透過 UITextViewDelegate 的 textViewDidChange 方法,就能攔截文字變動的訊息:
- (void)textViewDidChange:(UITextView *)textView {
NSLog(@"textViewDidChange:%@", textView.text);
}
小提醒:別忘了在標頭檔(.h)裡導入 UITextViewDelegate 協定,否則編譯時會給你顏色看。
除了文字變動,UITextViewDelegate 還提供了一整組編輯生命週期的鉤子,依需求挑著用:
把這些方法搭配起來,就能對文字輸入框的各種階段做出細緻的控制,例如彈出鍵盤、做輸入驗證或收起鍵盤時的收尾處理。