您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 鍵盤消失的四種方法:Delegate、Did on Exit、背景與按鈕

編輯:iOS 相關資訊

只要畫面中有 UITextField,就需要處理鍵盤何時收起。常見做法有四种。

1. UITextFieldDelegate

在 textFieldShouldReturn: 中呼叫 resignFirstResponder,讓按 Done 時收起鍵盤。

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

2. Did on Exit

在 Interface Builder 中把 Did on Exit 事件連到 IBAction,於 action 中呼叫 resignFirstResponder。

3. 背景 UIControl

把背景 view 改成 UIControl,因為 UIView 本身不接收事件,而 UIControl 可以。透過 Touch Down 事件讓鍵盤消失。

4. 全屏透明按鈕

放置一個覆蓋畫面的 UIButton,且必須放在最底層,避免影響輸入框接收事件。點擊非輸入區域時,在 action 中呼叫 resignFirstResponder。

- (IBAction)backgroundTap:(id)sender {
    [self.nameTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}

選擇建議

Delegate 與 UIControl 是較正規的做法;全屏按鈕與 Did on Exit 也能用,但維護性較差。最佳體驗通常同時處理 Done 鍵與點擊空白處。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved