1. 程式人生 > >iOS中UITextField常用設定和方法

iOS中UITextField常用設定和方法

//初始化textField並設定位置及大小 

UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, 30)];

// 當輸入框沒有內容時,水印提示 提示內容為"請輸入使用者名稱"

textField.placeholder = @"請輸入使用者名稱"

// 設定leftView左邊控制元件

// 設定leftView的frame時,x,y,height都是無效的,如果需要自定義,需要在外面新增一個view然後再在裡面進行操作

// textField.leftViewMode

UITextFieldViewModeNever 絕不顯示,預設的值

UITextFieldViewModeWhileEditing 當開始編輯的時候顯示

UITextFieldViewModeUnlessEditing 如果編輯,就不顯示

UITextFieldViewModeAlways 總是顯示

// 設定右邊控制元件 多用於傳送驗證碼等 //輸入框中最後面是否有個叉號,在什麼時候顯示,用於一次性刪除輸入框中的內容 text.clearButtonMode = UITextFieldViewWhileEditing; // 安全文字輸入(暗文) textField.secureTextEntry = YES; // 設定邊框樣式,只有設定了才會顯示邊框樣式 text.borderStyle = UITextBorderStyleRoundedRect; typedef enum { UITextBorderStyleNone, UITextBorderStyleLine, UITextBorderStyleBezel, UITextBorderStyleRoundedRect } UITextBorderStyle;
//設定輸入框的背景顏色,此時設定為白色 如果使用了自定義的背景圖片邊框會被忽略掉 text.backgroundColor = [UIColor whiteColor]; //設定背景 text.background = [UIImage imageNamed:@"dd.png"]; //設定背景 text.disabledBackground = [UIImage imageNamed:@"cc.png"]; //輸入框中一開始就有的文字 text.text = @"一開始就在輸入框的文字"; //是否糾錯, text.autocorrectionType = UITextAutocorrectionTypeNo; typedef
enum { UITextAutocorrectionTypeDefault, 預設 UITextAutocorrectionTypeNo,  不自動糾錯 UITextAutocorrectionTypeYes, 自動糾錯 } UITextAutocorrectionType; //再次編輯就清空 text.clearsOnBeginEditing = YES; //內容對齊方式 text.textAlignment = UITextAlignmentLeft; //內容的垂直對齊方式 UITextField繼承自UIControl,此類中有一個屬性contentVerticalAlignment text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; //設定為YES時文字會自動縮小以適應文字視窗大小.預設是保持原來大小,而讓長文字滾動 textFied.adjustsFontSizeToFitWidth = YES; //設定自動縮小顯示的最小字型大小 text.minimumFontSize = 20; //設定鍵盤的樣式 text.keyboardType = UIKeyboardTypeNumberPad; typedef enum { UIKeyboardTypeDefault,  預設鍵盤,支援所有字元 UIKeyboardTypeASCIICapable, 支援ASCII的預設鍵盤 UIKeyboardTypeNumbersAndPunctuation, 標準電話鍵盤,支援+*#字元 UIKeyboardTypeURL, URL鍵盤,支援.com按鈕 只支援URL字元 UIKeyboardTypeNumberPad,  數字鍵盤 UIKeyboardTypePhonePad,   電話鍵盤 UIKeyboardTypeNamePhonePad,  電話鍵盤,也支援輸入人名 UIKeyboardTypeEmailAddress,  用於輸入電子 郵件地址的鍵盤 UIKeyboardTypeDecimalPad,  數字鍵盤 有數字和小數點 UIKeyboardTypeTwitter,  優化的鍵盤,方便輸入@、#字元 UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, } UIKeyboardType; //首字母是否大寫 text.autocapitalizationType = UITextAutocapitalizationTypeNone; typedef enum { UITextAutocapitalizationTypeNone, 不自動大寫 UITextAutocapitalizationTypeWords, 單詞首字母大寫 UITextAutocapitalizationTypeSentences, 句子的首字母大寫 UITextAutocapitalizationTypeAllCharacters, 所有字母都大寫 } UITextAutocapitalizationType; //return鍵變成什麼鍵 text.returnKeyType =UIReturnKeyDone; typedef enum { UIReturnKeyDefault, 預設 灰色按鈕,標有Return UIReturnKeyGo,  標有Go的藍色按鈕 UIReturnKeyGoogle,標有Google的藍色按鈕,用語搜尋 UIReturnKeyJoin,標有Join的藍色按鈕 UIReturnKeyNext,標有Next的藍色按鈕 UIReturnKeyRoute,標有Route的藍色按鈕 UIReturnKeySearch,標有Search的藍色按鈕 UIReturnKeySend,標有Send的藍色按鈕 UIReturnKeyYahoo,標有Yahoo的藍色按鈕 UIReturnKeyYahoo,標有Yahoo的藍色按鈕 UIReturnKeyEmergencyCall, 緊急呼叫按鈕 } UIReturnKeyType; //鍵盤外觀 textView.keyboardAppearance=UIKeyboardAppearanceDefault; typedef enum { UIKeyboardAppearanceDefault, 預設外觀,淺灰色 UIKeyboardAppearanceAlert,   深灰 石墨色 } UIReturnKeyType; //設定代理 用於實現協議 text.delegate = self; //把textfield加到檢視中 [self.window addSubview:text]; //最右側加圖片是以下程式碼  左側類似 UIImageView *image=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]]; text.rightView=image; text.rightViewMode = UITextFieldViewModeAlways; typedef enum { UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing, UITextFieldViewModeAlways } UITextFieldViewMode; //按return鍵鍵盤往下收 becomeFirstResponder 類要採用UITextFieldDelegate協議 text.delegate = self; 宣告text的代理是我,我會去實現把鍵盤往下收的方法 這個方法在UITextFieldDelegate裡所以我們要採用UITextFieldDelegate這個協議 - (BOOL)textFieldShouldReturn:(UITextField *)textField { [text resignFirstResponder]; //主要是[receiver resignFirstResponder]在哪呼叫就能把receiver對應的鍵盤往下收 return YES; } 重寫繪製行為 除了UITextField物件的風格選項,你還可以定製化UITextField物件,為他新增許多不同的重寫方法,來改變文字欄位的顯示行為。這些方法都會返回一個CGRect結構,制定了文字欄位每個部件的邊界範圍。以下方法都可以重寫。 – textRectForBounds:    //重寫來重置文字區域 – drawTextInRect:    //改變繪文字屬性.重寫時呼叫super可以按預設圖形屬性繪製,若自己完全重寫繪製函式,就不用呼叫super了. – placeholderRectForBounds:  //重寫來重置佔位符區域 – drawPlaceholderInRect:  //重寫改變繪製佔位符屬性.重寫時呼叫super可以按預設圖形屬性繪製,若自己完全重寫繪製函式,就不用呼叫super了. – borderRectForBounds:  //重寫來重置邊緣區域 – editingRectForBounds:  //重寫來重置編輯區域 – clearButtonRectForBounds:  //重寫來重置clearButton位置,改變size可能導致button的圖片失真 – leftViewRectForBounds: – rightViewRectForBounds: 代理方法 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textFiel { //指定是否允許文字欄位開始編輯,預設是YES } - (void)textFieldDidBeginEditing:(UITextField *)textField { //開始編輯,文字欄位將成為 first responder } - (void)textFieldDidEndEditing:(UITextField *)textField { //獲取最後textField上的內容 } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField{ //返回BOOL值,指定是否允許文字欄位結束編輯,當編輯結束,文字欄位會讓出first responder //要想在使用者結束編輯時阻止文字欄位消失,可以返回NO //這對一些文字欄位必須始終保持活躍狀態的程式很有用,比如即時訊息 return NO; } - (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ //當用戶使用自動更正功能,把輸入的文字修改為推薦的文字時,就會呼叫這個方法。 //這對於想要加入撤銷選項的應用程式特別有用 //可以在該方法中對使用者輸入的資料進行校驗,符合要求才顯示,比如只能顯示數字 //要防止文字被改變可以返回NO //這個方法的引數中有一個NSRange物件,指明瞭被改變文字的位置,建議修改的文字也在其中 return YES; } - (BOOL)textFieldShouldClear:(UITextField *)textField{ //返回一個BOOL值指明是否允許根據使用者請求清除內容 //可以設定在特定條件下才允許清除內容 return YES; } -(BOOL)textFieldShouldReturn:(UITextField *)textField{ //返回一個BOOL值,指明是否允許在按下回車鍵時結束編輯 //如果允許要呼叫resignFirstResponder 方法,這回導致結束編輯,而鍵盤會被收起[textField resignFirstResponder]; //查一下resign這個單詞的意思就明白這個方法了 return YES; } 通知 UITextField繼承自UIControl,所以UIControl類中的通知系統在文字欄位中也可以使用。除了UIControl類的標準事件,你還可以使用下列UITextField類特有的事件 UITextFieldTextDidBeginEditingNotification UITextFieldTextDidChangeNotification UITextFieldTextDidEndEditingNotification 當文字欄位退出編輯模式時觸發。通知的object屬性儲存了最終文字。 因為文字欄位要使用鍵盤輸入文字,所以下面這些事件發生時,也會發送動作通知 UIKeyboardWillShowNotification  //鍵盤顯示之前傳送 UIKeyboardDidShowNotification  //鍵盤顯示之後傳送 UIKeyboardWillHideNotification  //鍵盤隱藏之前傳送 UIKeyboardDidHideNotification  //鍵盤隱藏之後傳送 限制只能輸入特定的字元 (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ NSCharacterSet *cs; cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet]; NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分離出陣列,陣列按@""分離出字串 BOOL canChange = [string isEqualToString:filtered]; return canChange; } 上面那個NUMBERS是一個巨集,可以在檔案頂部定義: #define NUMBERS @”0123456789n” (這個代表可以輸入數字和換行,請注意這個n,如果不寫這個,Done按鍵將不會觸發,如果用在SearchBar中,將會不觸發Search事件,因為你自己限制不讓輸入n) 所以,如果你要限制輸入英文和數字的話,就可以把這個定義為: #define kAlphaNum @”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″。 當然,你還可以在以上方法return之前,做一提示的,比如提示使用者只能輸入數字之類的。如果你覺得有需要的話。 限制只能輸入一定長度的字元 - (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string; {//string就是此時輸入的那個字元textField就是此時正在輸入的那個輸入框返回YES就是可以改變輸入框的值NO相反 if([stringisEqualToString:@"n"])//按會車可以改變 { returnYES; } NSString* toBeString = [textField.textstringByReplacingCharactersInRange:rangewithString:string];//得到輸入框的內容 if(self.myTextField == textField)//判斷是否時我們想要限定的那個輸入框 { if([toBeString length] >20) {//如果輸入框內容大於20則彈出警告 textField.text = [toBeString substringToIndex:20]; UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nilmessage:@"超過最大字數不能輸入了"delegate:nilcancelButtonTitle:@"Ok"otherButtonTitles:nil,nil] autorelease]; [alert show]; returnNO; } } returnYES; }