首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

iOS UITextView 清空技巧:故事板裡沒有 Clear Button 怎麼辦?

     編輯:程式設計疑難解答

問題場景

在 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 在鍵盤上方添加工具欄,放置「清空」等功能鍵,體驗更佳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved