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

UITextField 屬性與用法完整整理(給 iOS 新手的一份清單)

編輯:iOS 開發綜合

UITextField 是所有輸入框的基礎元件,屬性多、細節雜,第一次用往往只能查到眼前需要的那一兩個。這篇把常用屬性、delegate 方法與實戰技巧整理成一份可查的清單。

一、外觀與行為屬性

邊框與背景

  • borderStyle:設定邊框樣式,不設定就不會有邊框。可選 UITextBorderStyleNone、Line、Bezel、RoundedRect。
  • backgroundColor:輸入框背景色。一旦使用自訂背景圖,邊框樣式會被忽略。
  • background:自訂背景圖,僅在 UITextBorderStyleNone 時有效。
  • disabledBackground:控制項被停用時的背景圖。
text.borderStyle = UITextBorderStyleRoundedRect;
text.backgroundColor = [UIColor whiteColor];
text.background = [UIImage imageNamed:@"dd.png"];
text.disabledBackground = [UIImage imageNamed:@"cc.png"];

文字相關

  • text:初始文字。
  • placeholder:沒有內容時顯示的提示文字,一旦輸入即自動消失。
  • font/textColor:字體樣式與顏色。
  • textAlignment:水平對齊方式;contentVerticalAlignment 則控制垂直對齊(UITextField 繼承自 UIControl,這個屬性來自那裡)。
  • adjustsFontSizeToFitWidth:設為 YES 時文字會自動縮小以適應寬度,需搭配 minimumFontSize 設定下限;預設是維持原尺寸而讓長文字滾動。
  • clearsOnBeginEditing:再次進入編輯時清空原有內容。
  • secureTextEntry:輸入的每個字元立刻變成圓點,密碼欄必備。
  • clearButtonMode:右側清除鈕的顯示時機,可選 Never、WhileEditing、UnlessEditing、Always。
  • editing:是否允許編輯。
text.placeholder = @"password";
text.font = [UIFont fontWithName:@"Arial" size:20.0f];
text.textColor = [UIColor redColor];
text.textAlignment = UITextAlignmentLeft;
text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
text.adjustsFontSizeToFitWidth = YES;
text.minimumFontSize = 20;
text.clearButtonMode = UITextFieldViewModeAlways;
text.secureTextEntry = YES;

鍵盤相關

  • keyboardType:鍵盤配置。常用值包含 Default(全字元)、ASCIICapable、NumbersAndPunctuation、URL、NumberPad、PhonePad、NamePhonePad、EmailAddress、DecimalPad、Twitter(方便輸入 @ 與 #)。
  • autocapitalizationType:None/Words(單字首字母大寫)/Sentences(句首大寫)/AllCharacters(全大寫)。
  • autocorrectionType:是否啟用自動糾錯。
  • returnKeyType:右下角回車鈕的樣式,可為 Default、Go、Google、Join、Next、Route、Search、Send、Yahoo、EmergencyCall 等。
  • keyboardAppearance:Default(淺灰)或 Alert(深石墨色)。
  • inputView/inputAccessoryView:以前者取代系統鍵盤,後者則是在鍵盤上方加一條自訂工具列。
  • enablesReturnKeyAutomatically:預設 NO;設為 YES 時,輸入框沒有任何字元就無法按下回車鈕。
text.keyboardType = UIKeyboardTypeNumberPad;
text.autocapitalizationType = UITextAutocapitalizationTypeNone;
text.autocorrectionType = UITextAutocorrectionTypeNo;
text.returnKeyType = UIReturnKeyDone;

左右內嵌檢視

要在輸入框左右放圖示,用 leftView/rightView 搭配對應的 ViewMode:

UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];
text.rightView = image;
text.rightViewMode = UITextFieldViewModeAlways;

二、可覆寫的繪製方法

除了屬性,UITextField 也允許你透過覆寫方法自訂各部位的排版與繪製。以下方法都回傳 CGRect,用來決定各元件的邊界範圍:

  • textRectForBounds::重設文字區域。
  • editingRectForBounds::重設編輯狀態下的文字區域。
  • placeholderRectForBounds::重設提示文字區域。
  • borderRectForBounds::重設邊緣區域。
  • clearButtonRectForBounds::重設清除鈕位置(調整 size 可能造成圖形變形)。
  • leftViewRectForBounds:/rightViewRectForBounds::重設左右檢視位置。
  • drawTextInRect:/drawPlaceholderInRect::自訂文字與提示文字的繪製。呼叫 super 可保留預設樣式再微調;若完全自繪則不需呼叫 super。

三、UITextFieldDelegate 常用方法

類別需遵守 UITextFieldDelegate 協定並設定 text.delegate = self。最常用到的收鍵寫法:

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

其餘方法與時機:

  • textFieldShouldBeginEditing::回傳 YES 允許進入編輯,NO 則禁止。
  • textFieldDidBeginEditing::開始編輯,欄位成為 first responder。
  • textFieldShouldEndEditing::回傳 NO 可阻止結束編輯。對「必須保持活躍」的欄位(例如即時聊天輸入框)很實用。
  • textFieldDidEndEditing::結束編輯後呼叫。
  • textField:shouldChangeCharactersInRange:replacementString::字元變更前呼叫,回傳 NO 可拒絕這次變更。range 指出被改動的位置,replacementString 是新字串。這是做輸入格式限制的關鍵方法。
  • textFieldShouldClear::是否允許依使用者請求清除內容。

四、UITextField 的通知

UITextField 源自 UIControl,因此除了標準事件外,還有幾個專屬通知:UITextFieldTextDidBeginEditingNotification、UITextFieldTextDidChangeNotification、UITextFieldTextDidEndEditingNotification(離開編輯模式時觸發,通知的 object 屬性存有最終文字)。由於需要鍵盤輸入,鍵盤顯示與隱藏也會送出 UIKeyboardWillShowNotification、UIKeyboardDidShowNotification、UIKeyboardWillHideNotification、UIKeyboardDidHideNotification。

五、實戰技巧

限制只能輸入數字

做法是把字串依「反向字元集」切割再重新接合,若結果與原字串不同,代表含有不允許的字元:

#define NUMBERSPERIOD @"0123456789."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
  replacementString:(NSString *)string {

    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERSPERIOD] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    BOOL basicTest = [string isEqualToString:filtered];
    if (!basicTest) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                       message:@"請輸入數字"
                                                      delegate:nil
                                             cancelButtonTitle:@"確定"
                                             otherButtonTitles:nil];
        [alert show];
        [alert release];
        return NO;
    }
    return basicTest;
}

這裡有個很貴的教訓:字元集字串結尾那個 n(換行)千萬別漏。少了它,回車鍵不會觸發 shouldReturn,放在 SearchBar 裡則 search 事件完全不會發生——自己把換行擋掉了,卻很難察覺。

限制輸入長度

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
  replacementString:(NSString *)string {

    if ([string isEqualToString:@"\n"]) {
        return YES;
    }

    NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (self.myTextField == textField) {
        if ([toBeString length] > 20) {
            textField.text = [toBeString substringToIndex:20];
            UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil
                                                           message:@"超過最大字數不能輸入了"
                                                          delegate:nil
                                                 cancelButtonTitle:@"Ok"
                                                 otherButtonTitles:nil] autorelease];
            [alert show];
            return NO;
        }
    }
    return YES;
}

監聽「內容已改變」事件

UISearchBar 有 textDidChange 這類回呼,UITextField 沒有;而 shouldChangeCharactersInRange: 是在變更「之前」呼叫的。若需要變更「之後」的反應,改用 target-action 監聽 UIControlEventEditingChanged:

// 在 viewDidLoad 中註冊
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

// 回呼
- (void)textFieldDidChange:(id)sender {
    UITextField *_field = (UITextField *)sender;
    NSLog(@"%@", [_field text]);
}

六、Storyboard 上的欄位對照

介面產生器上的選項幾乎都對應到屬性,快速對照如下:Text(預設文字)、Placeholder(灰色提示)、Background/Disabled、對齊方式三顆鈕、Border Style、Clear Button(從不出現/編輯時出現/非編輯時出現/永遠顯示)、Clear when editing begins(開始編輯即清空)、Text Color、Font、Min Font Size、Adjust To Fit(尺寸縮小時文字跟著縮,但不會小於 Min Font Size)、Capitalization、Correction、Keyboard、Appearance、Return Key、Auto-enable Return Key、Secure。此外还有 Horizontal/Vertical 對齊,以及 Selected、Enabled、Highlighted 三個狀態回報。

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