您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

UITextField 全解:屬性、枚舉、代理與輸入限制

編輯:iOS 技巧大全

UITextField 是表單類需求的主力。它繼承自 UIControl,因此除了自身屬性外還能用整套 target-action 與通知機制。以下依「外觀 → 鍵盤 → 代理 → 輸入限制」四個區塊整理。

一、建立與外觀

// 建立並設定位置與大小
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(20, 20, 130, 30)];

// 邊框樣式,不設定就沒有邊框
text.borderStyle = UITextBorderStyleRoundedRect;

typedef enum {
    UITextBorderStyleNone,
    UITextBorderStyleLine,
    UITextBorderStyleBezel,
    UITextBorderStyleRoundedRect
} UITextBorderStyle;

// 背景色。若另外設了 background 圖片,borderStyle 會被忽略
text.backgroundColor = [UIColor whiteColor];

// 背景圖(正常狀態)
text.background = [UIImage imageNamed:@"dd.png"];

// 背景圖(不可編輯狀態)
text.disabledBackground = [UIImage imageNamed:@"cc.png"];

// 沒有內容時的灰色提示文字
text.placeholder = @"password";

// 字型與字級
text.font = [UIFont fontWithName:@"Arial" size:20.0f];

// 文字顏色
text.textColor = [UIColor redColor];

// 預設文字
text.text = @"一開始就在輸入框的文字";

清除按鈕

clearButtonMode 決定右側那個小叉號何時出現,用它可以一鍵清空內容。

text.clearButtonMode = UITextFieldViewModeAlways;

typedef enum {
    UITextFieldViewModeNever,          // 永不出現
    UITextFieldViewModeWhileEditing,   // 編輯時出現
    UITextFieldViewModeUnlessEditing,  // 除編輯外都出現
    UITextFieldViewModeAlways          // 一直出現
} UITextFieldViewMode;

左右內嵌視圖

rightView 與 leftView 常用來放放大鏡、眼睛圖示:

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

對齊與自動縮放

// 水平對齊
text.textAlignment = UITextAlignmentLeft;

// 垂直對齊,此屬性來自父類 UIControl
text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

// 設為 YES 時文字會自動縮小以適應寬度;預設是保持原大小並讓長文字滾動
text.adjustsFontSizeToFitWidth = YES;

// 自動縮小的下限字級
text.minimumFontSize = 20;

其他行為

// 每輸入一個字就顯示為圓點,用於密碼欄
text.secureTextEntry = YES;

// 是否自動糾錯
text.autocorrectionType = UITextAutocorrectionTypeNo;

typedef enum {
    UITextAutocorrectionTypeDefault,  // 預設
    UITextAutocorrectionTypeNo,       // 不自動糾錯
    UITextAutocorrectionTypeYes       // 自動糾錯
} UITextAutocorrectionType;

// 再次進入編輯時清空舊內容
text.clearsOnBeginEditing = YES;

// 首字母大寫策略
text.autocapitalizationType = UITextAutocapitalizationTypeNone;

typedef enum {
    UITextAutocapitalizationTypeNone,             // 不自動大寫
    UITextAutocapitalizationTypeWords,            // 單字首字母大寫
    UITextAutocapitalizationTypeSentences,        // 句子首字母大寫
    UITextAutocapitalizationTypeAllCharacters     // 全部大寫
} UITextAutocapitalizationType;

// 設定代理
text.delegate = self;

[self.window addSubview:text];

二、鍵盤相關

// 鍵盤樣式
text.keyboardType = UIKeyboardTypeNumberPad;

typedef enum {
    UIKeyboardTypeDefault,                 // 預設鍵盤,支援所有字元
    UIKeyboardTypeASCIICapable,            // 支援 ASCII 的預設鍵盤
    UIKeyboardTypeNumbersAndPunctuation,   // 電話鍵盤,支援 + * #
    UIKeyboardTypeURL,                     // 帶 .com 按鍵,僅支援 URL 字元
    UIKeyboardTypeNumberPad,               // 純數字
    UIKeyboardTypePhonePad,                // 電話鍵盤
    UIKeyboardTypeNamePhonePad,            // 電話鍵盤,另可輸入人名
    UIKeyboardTypeEmailAddress,            // 電子郵件地址專用
    UIKeyboardTypeDecimalPad,              // 數字含小數點
    UIKeyboardTypeTwitter,                 // 方便輸入 @ 與 #
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;

// return 鍵的樣式
text.returnKeyType = UIReturnKeyDone;

typedef enum {
    UIReturnKeyDefault,       // 灰色按鈕,標示 Return
    UIReturnKeyGo,            // 藍色 Go
    UIReturnKeyGoogle,        // 藍色 Google,用於搜尋
    UIReturnKeyJoin,          // 藍色 Join
    UIReturnKeyNext,          // 藍色 Next
    UIReturnKeyRoute,         // 藍色 Route
    UIReturnKeySearch,        // 藍色 Search
    UIReturnKeySend,          // 藍色 Send
    UIReturnKeyYahoo,         // 藍色 Yahoo
    UIReturnKeyEmergencyCall  // 緊急呼叫
} UIReturnKeyType;

// 鍵盤外觀
text.keyboardAppearance = UIKeyboardAppearanceDefault;

typedef enum {
    UIKeyboardAppearanceDefault,  // 預設淺灰
    UIKeyboardAppearanceAlert     // 深灰石墨色
} UIKeyboardAppearance;

三、代理方法

類別需採用 UITextFieldDelegate 協議,並設定 text.delegate = self。

// 按下 return 鍵時收起鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // 對哪個物件呼叫 resignFirstResponder,收的就是它對應的鍵盤
    [textField resignFirstResponder];
    return YES;
}
// 是否允許開始編輯
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

// 開始編輯,textField 將成為第一響應者
- (void)textFieldDidBeginEditing:(UITextField *)textField {
}

// 是否允許結束編輯。返回 NO 可阻止 textField 消失,
// 對即時通訊這類必須保持輸入列的場景很實用
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    return YES;
}

// 文字即將變更時呼叫,range 指出被改動的位置,string 是將插入的內容。
// 返回 NO 可阻止變更;也可用來實作撤銷、審計日誌
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
    return YES;
}

// 是否允許依使用者請求清除內容
- (BOOL)textFieldShouldClear:(UITextField *)textField {
    return YES;
}

// 是否允許在按下 return 鍵時結束編輯
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

四、限制輸入內容

只允許特定字元

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

    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];

    // 以不合規字元切開陣列,再用空字串拼回,剩下的即為合法內容
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]
                          componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
}

NUMBERS 是個巨集,在檔案頂部定義:

#define NUMBERS @"0123456789\n"

注意那個 \n 千萬別漏。若不含換行符,Done 鍵不會觸發;用在 UISearchBar 上則 Search 事件不會觸發——因為你自己禁止了換行輸入。這個坑我是在專案上才發現的。

若要允許英數混合:

#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

限制長度

- (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, nil];
            [alert show];
            return NO;
        }
    }
    return YES;
}

五、自訂繪製行為

除了屬性設定,UITextField 也允許覆寫一批方法來改變各部位的邊界與繪製方式。它們都回傳 CGRect,用來指定該部位的範圍:

- (CGRect)textRectForBounds:(CGRect)bounds;          // 文字區域
- (void)drawTextInRect:(CGRect)rect;                 // 文字繪製
- (CGRect)placeholderRectForBounds:(CGRect)bounds;   // 提示文字區域
- (void)drawPlaceholderInRect:(CGRect)rect;          // 提示文字繪製
- (CGRect)borderRectForBounds:(CGRect)bounds;        // 邊框區域
- (CGRect)editingRectForBounds:(CGRect)bounds;       // 編輯狀態下的文字區域
- (CGRect)clearButtonRectForBounds:(CGRect)bounds;   // 清除按鈕位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds;
- (CGRect)rightViewRectForBounds:(CGRect)bounds;

覆寫繪製方法時,若呼叫 super 就是沿用系統預設外觀;完全自繪則不必呼叫。調整 clearButtonRectForBounds: 的 size 要小心,改動過大會讓叉號圖片失真。

六、通知

UITextField 派生自 UIControl,因此 UIControl 的通知系統在此同樣適用。此外還有三個專屬通知:

UITextFieldTextDidBeginEditingNotification
UITextFieldTextDidChangeNotification
UITextFieldTextDidEndEditingNotification   // object 屬性存的是最終文字

由於輸入需要鍵盤,以下通知也會一併送出:

UIKeyboardWillShowNotification   // 顯示前
UIKeyboardDidShowNotification     // 顯示後
UIKeyboardWillHideNotification    // 隱藏前
UIKeyboardDidHideNotification     // 隱藏後

實務上處理鍵盤遮擋時,請用 Will 系列而非 Did 系列——Did 觸發時動畫已經跑完,你才去搬 view 就會明顯落後一拍。

七、Interface Builder 上的對應選項

Text 是預設文字;Placeholder 是灰色提示,輸入後自動消失;Disabled 打勾後使用者無法編輯;Border Style 選邊框風格;Clear Button 對應前面那個下拉選單(Never appears / Appears while editing / Appears unless editing / Is always visible);Clear when editing begins 等同 clearsOnBeginEditing;Text Color、Font、Min Font Size、Adjust To Fit 則各自對應同名屬性,其中 Adjust To Fit 需與 Min Font Size 搭配,文字再怎麼縮也不會小於設定的下限。

鍵盤區塊的 Capitalization、Correction、Keyboard、Appearance、Return Key、Auto-enable Return Key(至少輸入一個字元後 return 鍵才可用)、Secure(顯示為星號)也都能用程式碼達到相同效果。另外,Alignment 的 Horizontal 與 Vertical 對應 textAlignment 與 contentVerticalAlignment。

最後補充一個 IB 上查不到、但實際上很實用的技巧:利用 textFieldShouldReturn: 搭配 tag 或陣列,可以讓多個輸入框的 return 鍵變成「跳到下一欄」,這是填表類介面最基本的操作體驗。

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