登錄界面幾乎必然會遇到密碼輸入框。UITextField 提供了專門的屬性來處理這件事,實現方式有兩種。
在 Interface Builder 中選中對應的 UITextField,在屬性檢查器裡勾選 Secure Text Entry( secure 選項)即可。輸入時字符會以圓點顯示。
UITextField *test = [[UITextField alloc] init]; test.secureTextEntry = YES;
關鍵就是 secureTextEntry 這個布爾屬性。設為 YES 後,鍵盤的建議與自動更正也會自動關閉,這正是密碼場景所需要的行為。
單純設置 secureTextEntry 往往還不夠,一個完整的密碼輸入框通常還需要這些搭配:
UITextField *passwordField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 280, 40)]; passwordField.placeholder = @"請輸入密碼"; passwordField.secureTextEntry = YES; // 密文顯示 passwordField.keyboardType = UIKeyboardTypeDefault; // 默認鍵盤 passwordField.returnKeyType = UIReturnKeyDone; // 回車鍵顯示 Done passwordField.autocorrectionType = UITextAutocorrectionTypeNo; // 關閉自動更正 passwordField.autocapitalizationType = UITextAutocapitalizationTypeNone; // 關閉自動大寫 passwordField.clearButtonMode = UITextFieldViewModeWhileEditing; // 編輯時顯示清除按鈕 passwordField.delegate = self;
其中 autocorrectionType 與 autocapitalizationType 特別值得注意 —— 如果不關閉,用戶輸入時鍵盤上方會冒出候選詞,體驗很怪。
現在很多 App 提供「小眼睛」按鈕讓用戶切換明文與密文。實現起來很簡單,切換屬性即可:
- (void)togglePasswordVisible:(UIButton *)sender {
// 保存當前光標位置,切換後還原
NSUInteger cursorPosition = [self.passwordField offsetFromPosition:self.passwordField.beginningOfDocument
toPosition:self.passwordField.selectedTextRange.end];
self.passwordField.secureTextEntry = !self.passwordField.secureTextEntry;
// 重新成為第一響應者,否則切換後鍵盤會收起
[self.passwordField becomeFirstResponder];
UITextPosition *newPosition = [self.passwordField positionFromPosition:self.passwordField.beginningOfDocument
offset:cursorPosition];
self.passwordField.selectedTextRange = [self.passwordField textRangeFromPosition:newPosition
toPosition:newPosition];
}
這段代碼裡有兩個容易忽略的細節:切換 secureTextEntry 會導致鍵盤收起,所以必須重新調用 becomeFirstResponder;同時光標位置會跳到末尾,需要手動保存並還原,否則用戶在字符串中間編輯時會突然跳到尾部。
無論用 XIB 還是代碼,核心都是 secureTextEntry = YES 這一行。真正的功夫在於周邊配置:鍵盤類型、回車鍵樣式、關閉自動更正與自動大寫,以及明文/密文切換時的光標處理。