一、簡介
<<UITextField(文本框) : UITextField被用作項目中獲取用戶信息的重要控件.在App中UITextField是出現頻率最高的控件之一.
<<繼承關系:UITextField-->UIControl-->UIView-->UIResponder-->NSObject
格式為
1-->初始化(作用)
typedef NS_ENUM(NSInteger, UITextBorderStyle) {
UITextBorderStyleNone,
UITextBorderStyleLine,
UITextBorderStyleBezel,
UITextBorderStyleRoundedRect
};(如果屬性有枚舉類型的話,這里會有枚舉類型說明)
UITextField*textField = [[UITextFieldalloc]initWithFrame:CGRectMake(10,10,300,30)];? (這是具體的例子)
@property(nullable, nonatomic,copy) NSString *placeholder; // UITextField?設置提示文字 ? ?(這是說明)
二、UITextField的文本屬性(屬性的順序與蘋果API一致)
1-->設置文字
textField.text?=?@"我是文本框";//設置文字
@property(nullable, nonatomic,copy) NSString *text;//設置顯示文字,?默認是空的
2-->設置富文本
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];-->先把UITextField上的文字賦值給可變字符串
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5,10)];-->設置更改后的顏色和改變文字的區(qū)域
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(20, 25)];-->設置更改后的字體大小和改變文字的區(qū)域
textField.attributedText = str;-->把改后的字符串重新賦值給UITextField

@property(nullable, nonatomic,copy) NSAttributedString *attributedText; //更改任意文字的顏色和字體大小
3-->設置文字顏色
textField.textColor = [UIColor redColor];//設置文字顏色
@property(nullable, nonatomic,strong) UIColor *textColor;// 默認是不透明的黑色
4-->設置字號//一般方法
textField.font = [UIFont systemFontOfSize:30];
@property(null_resettable, nonatomic,strong) UIFont *font;// ?設置字體(系統字體默認12號字體)
5-->文字字體加粗//系統加粗方法
[textField setFont:[UIFont boldSystemFontOfSize:25]];
6-->自定義文字字體和字號
textField.font = [UIFont fontWithName:@"Zapfino"size:30];
7-->自定義文字字體加粗和字號
[textFieldl setFont:[UIFont fontWithName:@"Helvetica-Bold"size:25]];
8-->文字對齊方式
typedef NS_ENUM(NSInteger, NSTextAlignment) {
NSTextAlignmentLeft? ? ? = 0,? ? // 居左對齊
#if TARGET_OS_IPHONE
NSTextAlignmentCenter? ? = 1,? ? //居中對齊
NSTextAlignmentRight? ? = 2,? ? //?居右對齊
#else /* !TARGET_OS_IPHONE */
NSTextAlignmentRight? ? = 1,? ? //居右對齊
NSTextAlignmentCenter? ? = 2,? ? //居中對齊
#endif
NSTextAlignmentJustified = 3,? ? //合理鋪滿 等同于居左
NSTextAlignmentNatural? = 4,? ? //默認 等同于居左
}
textField.textAlignment = NSTextAlignmentCenter;
@property(nonatomic)? ? ? ? NSTextAlignment? ? textAlignment;//? 對齊方式,默認是NSTextAlignmentNatural?(iOS 9之前, 默認是 NSTextAlignmentLeft)
默認都是豎直居中的
UITextField不能設置豎直方向的排列布局,但是可以通過sizeToFit改變UITextField的frame來實現曲線救國。
9-->設置邊框樣式,只有設置了才會顯示邊框樣式
typedef NS_ENUM(NSInteger, UITextBorderStyle) {
UITextBorderStyleNone,//無邊框
UITextBorderStyleLine,//線性矩形
UITextBorderStyleBezel,//尖角矩形
UITextBorderStyleRoundedRect//圓角矩形
};
textField.borderStyle=?UITextBorderStyleNone;
@property(nonatomic) UITextBorderStyle borderStyle; //默認是UITextBorderStyleNone。如果設置為UITextBorderStyleRoundedRect、自定義背景圖片將被忽略。
10-->設置默認字體屬性
[textField setDefaultTextAttributes: @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light" size:20.0], NSForegroundColorAttributeName: [UIColor redColor]} ];//設置默認字體與文本顏色
@property(nonatomic,copy) NSDictionary*defaultTextAttributes;//將屬性應用于文本的全部范圍。未設置的屬性表現為默認值。
11-->設置缺省時顯示的灰度字符串
textField.placeholder = @"password";//當輸入框沒有內容時,水印提示提示內容為password
@property(nullable, nonatomic,copy) NSString *placeholder; //默認是70%的灰色
12-->通過AttributedString設置缺省字符串
NSMutableAttributedString *verifyStr = [[NSMutableAttributedString alloc]initWithString:@"請輸入驗證碼" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName: [UIColor colorWithRed:181/255.0 green:181/255.0 blue:181/255.0 alpha:1.0]}];
[_VerifyTF setAttributedPlaceholder:verifyStr];//設置缺省字符串文本、字號和顏色等屬性
@property(nullable, nonatomic,copy) NSAttributedString *attributedPlaceholder;?
13-->設置再次編輯就清空
text.clearsOnBeginEditing = YES;//開啟再次編輯就清空
@property(nonatomic) BOOL clearsOnBeginEditing; //設置UITextField是否擁有一鍵清除的功能,默認為NO
14-->設置UITextField自適應文本框大小
textField.adjustsFontSizeToFitWidth = YES;//設置文字自適應寬度
@property(nonatomic) BOOL adjustsFontSizeToFitWidth;
//設置調整文字大小以適配寬度(即輸入不下時縮小文字,實在縮小不了了,就向下滾動),默認是向右滾動的
15-->設置自動縮小顯示的最小字體大小
textField.minimumFontSize = 20;//設置最小字體大小
@property(nonatomic) CGFloat minimumFontSize; //.默認是0.0。設置最小字號,在adjustsFontSizeToFitWidth?=?YES,才有效,即小于這個字號的時候,我就不縮小了,直接向右滾動
15-->設置UITextFieldDelegate代理
textField.delegate = self;//設置UITextField Delegate代理
@property(nullable, nonatomic,weak) id <UITextFieldDelegate>delegate; //弱引用
三、設置UITextField的背景屬性
1-->設置背景圖片
textField.background=?[UIImageimageNamed:@"1.png"];
@property(nullable, nonatomic,strong) UIImage *background; //繪制邊框,圖像應可伸縮
2-->設置禁用時的背景圖片
textField.disabledBackground = [UIImage imageNamed:@"cc.png"];//設置enable為no時,textfield的背景
@property(nullable, nonatomic,strong) UIImage *disabledBackground;(默認 nil,忽略背景不設置。圖片可能會被拉伸.)當UITextField被禁用時,顯示文本的背景圖片。
四、UITextField的編輯屬性
1-->讀取是否正在編輯(只讀屬性)
? BOOL editing=text.editing?;
@property(nonatomic,readonly,getter=isEditing) BOOL editing;
2-->是否允許更改字符屬性字典
textField.allowsEditingTextAttributes=YES;
@property(nonatomic) BOOL allowsEditingTextAttributes; //
默認是NO。允許用樣式操作編輯文本屬性并粘貼富文本
3-->設置屬性字典
NSMutableDictionary * attributesDic = [textView.typingAttributes mutableCopy];
[attributesDic setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
// automatically resets when the selection changes
// 重新設置 接下來改變的文字 的屬性字典
textField.typingAttributes = attributesDic;
@property(nullable, nonatomic,copy) NSDictionary*typingAttributes NS_AVAILABLE_IOS(6_0); //.(當選中文本時,自動復位)適用于用戶輸入的新文本的屬性。字典包含適用于新類型文本的屬性鍵(和對應的值)。當文本字段的選擇更改時,自動清除字典的內容。如果文本字段不是編輯模式,此屬性包含值為零。類似地,除非文本字段當前處于編輯模式,否則不能將此屬性賦值給該屬性
4-->設置是否顯示清除按鈕
typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
UITextFieldViewModeNever,//從不顯示
UITextFieldViewModeWhileEditing,//編輯時顯示
UITextFieldViewModeUnlessEditing,//非編輯時顯示
UITextFieldViewModeAlways//一直顯示
};
myTextField.clearButtonMode = UITextFieldViewModeAlways;//一直顯示清除按鈕
@property(nonatomic) UITextFieldViewMode clearButtonMode; //當清除按鈕出現時設置。默認是UITextFieldViewModeNever
五、UITextField的View屬性
1-->設置輸入框左邊的view
UIView *view1=[[UIView alloc]init];
//x和y無效,x都是0,而y是根據高度來自動調整的。即高度如果超過textField則默認是textField高,如小于textField高度,則上下居中顯示。唯一有效的就是寬度
view1.frame=CGRectMake(10, 500, 50, 10);
view1.backgroundColor=[UIColor orangeColor];
textFiled1.leftView=view1;
@property(nullable, nonatomic,strong) UIView *leftView; //?左側 view 視圖,例如搜索欄當中的放大鏡。要配合 leftViewMode 使用。
2-->設置輸入框左視圖的顯示模式
typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
UITextFieldViewModeNever,//從不顯示
UITextFieldViewModeWhileEditing,//編輯時顯示
UITextFieldViewModeUnlessEditing,//非編輯時顯示
UITextFieldViewModeAlways//一直顯示
};
textFiled.leftViewMode=UITextFieldViewModeAlways;
@property(nonatomic) UITextFieldViewMode leftViewMode; //當左邊視圖出現時設置。默認是UITextFieldViewModeNever
3-->設置輸入框右邊的view
UIView *view1=[[UIView alloc]init];
//x和y無效,x都是0,而y是根據高度來自動調整的。即高度如果超過textField則默認是textField高,如小于textField高度,則上下居中顯示。唯一有效的就是寬度
view1.frame=CGRectMake(10, 500, 50, 10);
view1.backgroundColor=[UIColor orangeColor];
textFiled1.rightView=view1;
@property(nullable, nonatomic,strong) UIView *rightView; // 右側 view 視圖,例如書簽按鈕。要配合 rightViewMode 使用。
4-->設置輸入框右視圖的顯示模式
typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
UITextFieldViewModeNever,//從不顯示
UITextFieldViewModeWhileEditing,//編輯時顯示
UITextFieldViewModeUnlessEditing,//非編輯時顯示
UITextFieldViewModeAlways//一直顯示
};
textFiled.rightViewMode=UITextFieldViewModeAlways;
@property(nonatomic) UITextFieldViewMode rightViewMode; //當右邊視圖出現時設置。默認是UITextFieldViewModeNever
六、UITextField的界面重寫繪制
1-->重寫重置邊緣區(qū)域
-(CGRect)borderRectForBounds:(CGRect)bounds{
return CGRectInset(bounds,10,0);
}
- (CGRect)borderRectForBounds:(CGRect)bounds;
2-->重寫重置文字區(qū)域
-(CGRect)textRectForBounds:(CGRect)bounds{
returnCGRectInset(bounds,10,0);
}
- (CGRect)textRectForBounds:(CGRect)bounds;
3-->重寫重置占位符區(qū)域
-(CGRect)placeholderRectForBounds:(CGRect)bounds{
returnCGRectInset(bounds,10,0);
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds;
4-->重寫重置編輯區(qū)域
-(CGRect)editingRectForBounds:(CGRect)bounds{
returnCGRectInset(bounds,10,0);
}
- (CGRect)editingRectForBounds:(CGRect)bounds;
5-->重寫來重置clearButton位置,改變size可能導致button的圖片失真
-(CGRect)clearButtonRectForBounds:(CGRect)bounds{
returnCGRectInset(bounds,10,0);
}
- (CGRect)clearButtonRectForBounds:(CGRect)bounds;
6-->重寫輸入框左視圖區(qū)域
-(CGRect)leftViewRectForBounds:(CGRect)bounds{
returnCGRectInset(bounds,10,0);
}
- (CGRect)leftViewRectForBounds:(CGRect)bounds;
7-->重寫輸入框右視圖區(qū)域
-(CGRect)rightViewRectForBounds:(CGRect)bounds{
returnCGRectInset(bounds,10,0);
}
- (CGRect)rightViewRectForBounds:(CGRect)bounds;
8-->重載drawTextInRect方法
-(void) drawTextInRect:(CGRect)rect {
return[super drawTextInRect:UIEdgeInsetsInsetRect(rect,self.neiinsets)];
}
-(void) drawTextInRect:(CGRect)rect;
9-->重載drawPlaceholderInRect方法
-(void) drawPlaceholderInRect:(CGRect)rect {
return[super drawPlaceholderInRect:UIEdgeInsetsInsetRect(rect,self.neiinsets)];
}
-(void) drawPlaceholderInRect:(CGRect)rect;
七、UITextField的鍵盤屬性
1-->當文本字段成為第一響應者時,自定義輸入視圖顯示。
UIImageView *imgView1=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"logo-60@3x.png"]];
imgView1.frame=CGRectMake(60, 60, 300, 300);
textFiled.inputView=imgView1;
@property (nullable, readwrite, strong) UIView *inputView;//只有height值會對視圖有影響,只會改變附加視圖的高度,彈出添加的這個視圖,一般用作像銀行app的自定義鍵盤
2-->當文本字段成為第一響應者時,該自定義輔助視圖顯示。
UIView * view = [[UIView alloc] initWithFrame:CGRectMake(100, 50, 100, 50)];
view.backgroundColor = [UIColor redColor];
// 在鍵盤上附加一個視圖,一般用于添加一個收回鍵盤的按鈕
textFiled.inputAccessoryView = view;
@property (nullable, readwrite, strong) UIView *inputAccessoryView;// 在鍵盤上附加一個視圖,一般用于添加一個收回鍵盤的按鈕
3-->注銷第一響應(収鍵盤)
[self.view endEditing:YES];
- (BOOL)endEditing:(BOOL)force;//注銷當前view(或它下屬嵌入的text fields)的first responder 狀態(tài)。
八、UITextField的UITextFieldDelegate代理方法
可選方法
1-->點擊輸入框時觸發(fā)的方法,返回YES則可以進入編輯狀態(tài),NO則不能。
#pragma mark - UITextField代理方法
/** 將要開始編輯
@param textField UITextField對象
@return YES:允許編輯; NO:禁止編輯?
*/
-?(BOOL)textFieldShouldBeginEditing:(UITextField*)textField{
//返回一個BOOL值,指定是否循序文本字段開始編輯
return?YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField; //.當文本將要開始編輯時調用這個代理方法,返回 NO 時駁回編輯狀態(tài)。
2-->開始編輯時調用的方法
/**?
開始編輯,即成為第一響應者,此時光標出現
@param textField UITextField對象?
*/
-?(void)textFieldDidBeginEditing:(UITextField*)textField{
//開始編輯時觸發(fā),文本字段將成為first?responder
}
- (void)textFieldDidBeginEditing:(UITextField *)textField; //當文本正在開始編輯時調用,變?yōu)榈谝豁憫?/p>
3-->將要結束編輯時調用的方法,返回YES則可以結束編輯狀態(tài),NO則不能
/**
將要結束編輯
應用場景:如果當前TextField有內容,則返回YES,允許收鍵盤或更換TextField;
當前TextField沒有輸入內容,返回NO,此時不能收起鍵盤或者更換TextField
@param textField UITextField對象
@returnYES:允許釋放鍵盤(注銷第一響應者); NO:不允許釋放鍵盤(始終是第一響應者)
*/
-?(BOOL)textFieldShouldEndEditing:(UITextField*)textField{
//返回BOOL值,指定是否允許文本字段結束編輯,當編輯結束,文本字段會讓出first?responder
//要想在用戶結束編輯時阻止文本字段消失,可以返回NO
//這對一些文本字段必須始終保持活躍狀態(tài)的程序很有用,比如即時消息
return?NO;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField; //當文本將要結束編輯時進行調用,返回 YES 時允許編輯停止或者注銷第一響應者,返回 NO,不允許編輯會話結束。
4-->結束編輯調用的方法
/**
已經結束編輯
(即使shouldEndEditing方法返回NO或者調用了endEditing:YES,該方法仍可能調用)
官方注釋:may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
@param textField UITextField對象
*/
-?(void)textFieldDidEndEditing:(UITextField*)textField{
//結束編輯時觸發(fā)
}
- (void)textFieldDidEndEditing:(UITextField *)textField;?
//上面返回YES后執(zhí)行;上面返回NO時有可能強制執(zhí)行(e.g.view removed from window)
5-->結束編輯調用的方法(iOS 10.0開始引入)
/**
已經結束編輯(iOS 10.0開始引入)
如果實現,將取代textFieldDidEndEditing:方法
@param textField UITextField對象
@param reason 結束原因(正常代理結束或者被迫取消)
*/
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason {
//結束編輯時觸發(fā)(iOS 10.0開始引入)
}
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason NS_AVAILABLE_IOS(10_0) ;//如果實現,將取代textFieldDidEndEditing:方法
6-->將要改變文字內容時調用的方法
/**
將要改變文字內容時
應用場景:
1.撤銷上一次輸入
2.跟蹤本TextField所做的最后一次修改
3.防止文字被改變
4.限制輸入字符類型
@param textField UITextField對象
@param range 被修改內容的范圍
@param string 修改內容取代者
@return ?YES:允許修改; NO:不允許修改
*/
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
returnYES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; //詢問代理文本是否可以被替換,如果返回 NO,不被替換,YES 可被替換。
7-->當按下清除按鈕時調用的方法
/**
當按下清除按鈕時
@param textField UITextField對象
@return YES:允許清除; NO:不許清除
?*/
- (BOOL)textFieldShouldClear:(UITextField *)textField {
return YES;
}
- (void)textFieldShouldClear:(UITextField *)textField;
8-->按下鍵盤返回鍵調用的方法
/**
按下鍵盤返回鍵時
應用舉例:調用resignFirstResponder方法收回鍵盤
@param textField UITextField對象
@return 我發(fā)現返回YES或NO,效果都一樣...
*/
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
return [textField resignFirstResponder];
}
- (void)textFieldShouldReturn:(UITextField *)textField;
九、UITextField的通知
UITextField派生自UIControl,所以UIControl類中的通知系統在文本字段中也可以使用。除了UIControl類的標準事件,你還可以使用下列UITextField類特有的事件
UITextFieldTextDidBeginEditingNotification
UITextFieldTextDidChangeNotification
UITextFieldTextDidEndEditingNotification
當文本字段退出編輯模式時觸發(fā)。通知的object屬性存儲了最終文本。
因為文本字段要使用鍵盤輸入文字,所以下面這些事件發(fā)生時,也會發(fā)送動作通知
UIKeyboardWillShowNotification //鍵盤顯示之前發(fā)送
UIKeyboardDidShowNotification? //鍵盤顯示之后發(fā)送
UIKeyboardWillHideNotification //鍵盤隱藏之前發(fā)送
UIKeyboardDidHideNotification? //鍵盤隱藏之后發(fā)送
十、UITextField的UITextFieldDelegate代理方法拓展
1-->限制輸入字符類型
在代理方法中作判斷,符合返回YES,不符合返回NO。
例如匹配輸入為純數字:
/**
將要改變文字內容時
?應用場景:
1.撤銷上一次輸入
?2.跟蹤本TextField所做的最后一次修改
?3.防止文字被改變
?4.限制輸入字符類型
@param textField UITextField對象
@param range 被修改內容的范圍
@param string 修改內容取代者
@returnYES:允許修改; NO:不允許修改?
*/
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// 匹配純數字NSString *regex = @"[0-9]";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return[pred evaluateWithObject:string];// 匹配返回YES,否則返回NO
}
2-->限制輸入字符個數
字符個數決定了字符串的長度。
在代理方法中很難實時地獲得字符串長度,因此不好在代理方法里判斷。好在蘋果提供了監(jiān)聽UITextField的編輯發(fā)生改變的事件,可在該事件中作判斷。
首先要添加事件:
[textField addTarget:selfaction:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];
// 當編輯發(fā)生改變
- (void)textFieldDidChange:(UITextField*)textField{
// 獲取字符串長度
NSUInteger strLength =0;
for (NSUInteger I=0; I<textField.text.length; i++) {
unichar uc = [textField.textcharacterAtIndex: I];
strLength += isascii(uc) ?1:2;// 漢字兩個字節(jié)
}
// 如果字符串大于5,裁掉后尾
if(strLength >5) {
textField.text= [textField.text substringToIndex:5];
}
}