4. iOS 編程 之 UITextFiled
前面提了按鈕,那接下來給大家看一下 UITextField 怎麼用。
代碼:AppdDelegate.m
//定義變數UITextField *textField;- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; UIViewController *viewController = [UIViewController alloc]; self.window.rootViewController = viewController; UIView *rootView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; viewController.view = rootView; /******************** UITextField ********************/ //建立 UITextField textField = [[UITextField alloc] init]; //設定UITextField的位置,寬高 textField.frame = CGRectMake(100, 100, 200, 30); /** * 設定邊框樣式,有如下枚舉值: * UITextBorderStyleNone(沒格式) * UITextBorderStyleLine(線條) * UITextBorderStyleBezel(3D) * UITextBorderStyleRoundedRect(圓角) */ textField.borderStyle = UITextBorderStyleRoundedRect; //設定背景顏色 textField.backgroundColor = [UIColor yellowColor]; //設定預設輸入文字 //textField.text = @"text"; //設定提示性的文字 textField.placeholder = @"Jss"; //重新編輯會自動清除原有的內容 textField.clearsOnBeginEditing = YES; //文字的最小值 //textField.minimumFontSize = 10.0f; //文字自動隨著文字框的減小而縮小 textField.adjustsFontSizeToFitWidth = YES; /** * 自動轉換文字框內輸入文本的大小 * UITextAutocapitalizationTypeNone(不切換) * UITextAutocapitalizationTypeWords(每個單詞的首字母) * UITextAutocapitalizationTypeSentences(每個句子的首字母) * UITextAutocapitalizationTypeAllCharacters(所有字母) */ textField.autocapitalizationType = UITextAutocapitalizationTypeWords; /** * 設定鍵盤的類型 * UIKeyboardTypeDefault(預設的鍵盤) * UIKeyboardTypeASCIICapable(英文字母鍵盤) * UIKeyboardTypeNumbersAndPunctuation(數字和標點符號鍵盤) * UIKeyboardTypeURL(URL鍵盤) * UIKeyboardTypeNumberPad(數字鍵台) * UIKeyboardTypePhonePad(電話鍵盤) * UIKeyboardTypeNamePhonePad(個性電話鍵盤) * UIKeyboardTypeEmailAddress(輸入E-mail地址的鍵盤) * UIKeyboardTypeDecimalPad(可輸入數字和小數點的鍵盤) * UIKeyboardTypeTwitter(Twitter鍵盤) * UIKeyboardTypeWebSearch(網頁搜尋鍵盤) */ textField.keyboardType = UIKeyboardTypeNamePhonePad; /** * 設定清除按鈕類型 * UITextFieldViewModeNever(從不顯示清除按鈕) * UITextFieldViewModeWhileEditing(當編輯時顯示清除按鈕) * UITextFieldViewModeUnlessEditing(除了編輯外都顯示清除按鈕) * UITextFieldViewModeAlways(清除按鈕一直出現) */ textField.clearButtonMode = UITextFieldViewModeWhileEditing; //添加UITextField到view [rootView addSubview:textField]; [self.window makeKeyAndVisible]; return YES;}/** * 釋放鍵盤 */- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [textField resignFirstResponder];}運行結果:
值得說的是,最後一段 touchesBegan: 方法。如果沒有這一段代碼,那麼當你在輸入框內輸入完成之後,鍵盤是不會自動收回去的。所以,我們要擷取當前響應,然後關掉鍵盤。務必熟記,特別重要。
基礎部分,簡單介紹一下就行,以後碰到相關的再接著說明其他的使用方法。
第四章,結束!
本篇內容屬原創,轉載請註明出處,禁止用於商業用途。謝謝!