您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

以程式碼手工建立 UITextField 並控制鍵盤

編輯:iOS 開發綜合

用 Storyboard 拉元件雖然直觀,但在需要動態生成表單、或元件數量由資料決定時,用程式碼建立 UITextField 反而更靈活。以下整理建立時常設定的屬性,以及鍵盤的顯示與隱藏。

一、建立與初始化設定

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
textField.borderStyle = UITextBorderStyleRoundedRect;                  // 圓角外框
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = @"enter text";                                // 未輸入時的提示文字
textField.autocorrectionType = UITextAutocorrectionTypeNo;            // 關閉自動更正
textField.keyboardType = UIKeyboardTypeDefault;                       // 一般鍵盤
textField.returnKeyType = UIReturnKeyDone;                            //  return 鍵顯示 Done
textField.clearButtonMode = UITextFieldViewModeWhileEditing;          // 編輯時出現清除鈕
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.delegate = self;

[self.view addSubview:textField];

二、常用 keyboardType 選項

依輸入內容選擇合適的鍵盤,能明顯改善使用者體驗:

  • UIKeyboardTypeDefault:一般全鍵盤
  • UIKeyboardTypeNumbersAndPunctuation:數字加標點
  • UIKeyboardTypeNumberPad:純數字,適合 PIN 碼
  • UIKeyboardTypePhonePad:電話號碼格式
  • UIKeyboardTypeEmailAddress: email 輸入,@ 與 . 直接可見
  • UIKeyboardTypeURL:網址輸入
  • UIKeyboardTypeNamePhonePad:中英混排的姓名欄位

三、叫出與收起鍵盤

鍵盤的顯示與隱藏其實就是「第一響應者」的取得與放棄。

// 主動讓輸入框取得焦點,鍵盤彈出
[textField becomeFirstResponder];

// 讓輸入框放棄焦點,鍵盤收起
[textField resignFirstResponder];

四、相關的 delegate 方法

// 即將開始編輯,回傳 NO 可阻止鍵盤彈出
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [textField becomeFirstResponder];
    return YES;
}

// 按下 return 鍵時呼叫,適合在此收鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

// 即將結束編輯,回傳 NO 可阻止收鍵盤
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    return YES;
}

// 點擊清除鈕時呼叫
- (BOOL)textFieldShouldClear:(UITextField *)textField {
    return YES;
}

實務小技巧

若畫面上有多個輸入框,按下 return 應該跳到下一個而不是直接收鍵盤。可以在 textFieldShouldReturn 裡改用另一個輸入框的 becomeFirstResponder,並依 returnKeyType 是 Next 還是 Done 決定行為。

另外別忘了處理鍵盤遮住輸入框的問題:可監聽 UIKeyboardWillShowNotification 與 UIKeyboardWillHideNotification,在通知回呼中調整 scrollView 的 contentInset。

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