在 Storyboard 中拖拽 UITextView 時,發現屬性檢查器裡沒有像 UITextField 那樣的 Clear Button 選項。想點擊一次按鈕清空所有文字,逐個刪除太麻煩。
雖然 UITextView 沒有內建清除按鈕,但系統提供了直觀的交互:
長按鍵盤上的刪除鍵(Backspace),即可觸發連續刪除,效果等同於 Clear Button。
若需在界面顯式放置清除按鈕,可通過代碼實現:
// 在 UITextView 右側添加清除按鈕
UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeSystem];
[clearBtn setTitle:@"×" forState:UIControlStateNormal];
[clearBtn addTarget:self action:@selector(clearTextView:) forControlEvents:UIControlEventTouchUpInside];
textView.rightView = clearBtn;
textView.rightViewMode = UITextFieldViewModeWhileEditing;
// 事件處理
- (void)clearTextView:(id)sender {
self.textView.text = @"";
}
或使用 inputAccessoryView 在鍵盤上方添加工具欄,放置「清空」等功能鍵,體驗更佳。