你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS技巧綜合 >> 你真的了解UITextField嗎?

你真的了解UITextField嗎?

編輯:IOS技巧綜合
[摘要]本文是對你真的了解UITextField嗎?的講解,對學習IOS蘋果軟件開發有所幫助,與大家分享。

一:首先查看一下關於UITextField的定義

NS_CLASS_AVAILABLE_IOS(2_0) @interface UITextField : UIControl <UITextInput, NSCoding> 

@property(nullable, nonatomic,copy)   NSString               *text;        //值         
@property(nullable, nonatomic,copy)   NSAttributedString     *attributedText NS_AVAILABLE_IOS(6_0);  //富文本的值
@property(nullable, nonatomic,strong) UIColor                *textColor;            // 文字色
@property(nullable, nonatomic,strong) UIFont                 *font;                 // 字體
@property(nonatomic)        NSTextAlignment         textAlignment;        // 默認值 NSLeftTextAlignment 排版
@property(nonatomic)        UITextBorderStyle       borderStyle;          // 默認值 UITextBorderStyleNone 邊框的樣式
@property(nonatomic,copy)   NSDictionary<NSString *, id>           *defaultTextAttributes NS_AVAILABLE_IOS(7_0); // 文本屬性 用字典填充

@property(nullable, nonatomic,copy)   NSString               *placeholder;          // 空值時的提示文字
@property(nullable, nonatomic,copy)   NSAttributedString     *attributedPlaceholder NS_AVAILABLE_IOS(6_0); // 富文本的空值提示文字
@property(nonatomic)        BOOL                    clearsOnBeginEditing; // 默認值 NO 如果設為YES 再次編輯就清空
@property(nonatomic)        BOOL                    adjustsFontSizeToFitWidth; // 默認值NO,若設為YES 當文字超出文本框寬度時,自動調整文字大小
@property(nonatomic)        CGFloat                 minimumFontSize;      // 默認值 0.0.最小可縮小的字號和adjustsFontSizeToFitWidth一起使用
@property(nullable, nonatomic,weak)   id<UITextFieldDelegate> delegate;         //代理    
@property(nullable, nonatomic,strong) UIImage                *background;           //設置背景 注意只有UITextBorderStyleNone的時候改屬性有效
@property(nullable, nonatomic,strong) UIImage                *disabledBackground;   //禁用的背景

@property(nonatomic,readonly,getter=isEditing) BOOL editing;  //是否被編輯
@property(nonatomic) BOOL allowsEditingTextAttributes NS_AVAILABLE_IOS(6_0); // 默認值 NO
@property(nullable, nonatomic,copy) NSDictionary<NSString *, id> *typingAttributes NS_AVAILABLE_IOS(6_0); 


@property(nonatomic)        UITextFieldViewMode  clearButtonMode; // 輸入框中是否有個叉號 設置清除 何時顯示

@property(nullable, nonatomic,strong) UIView              *leftView;        //  左邊視圖
@property(nonatomic)        UITextFieldViewMode  leftViewMode;    // 在什麼狀態下顯示 默認值 UITextFieldViewModeNever

@property(nullable, nonatomic,strong) UIView              *rightView;       // 右邊視圖
@property(nonatomic)        UITextFieldViewMode  rightViewMode;   // 默認值 UITextFieldViewModeNever

//界面重寫繪制行為
////重寫來重置邊緣區域
- (CGRect)borderRectForBounds:(CGRect)bounds;
//重寫來重置文字區域
- (CGRect)textRectForBounds:(CGRect)bounds;
//重寫來重置占位符區域
- (CGRect)placeholderRectForBounds:(CGRect)bounds;
//重寫來重置編輯區域
- (CGRect)editingRectForBounds:(CGRect)bounds;
//重寫來重置clearButton位置,改變size可能導致button的圖片失真
- (CGRect)clearButtonRectForBounds:(CGRect)bounds;
- (CGRect)leftViewRectForBounds:(CGRect)bounds;
- (CGRect)rightViewRectForBounds:(CGRect)bounds;

//改變繪文字屬性.重寫時調用super可以按默認圖形屬性繪制,若自己完全重寫繪制函數,就不用調用super了.
- (void)drawTextInRect:(CGRect)rect;
//重寫改變繪制占位符屬性.重寫時調用super可以按默認圖形屬性繪制,若自己完全重寫繪制函數,就不用調用super了.
- (void)drawPlaceholderInRect:(CGRect)rect;

@property (nullable, readwrite, strong) UIView *inputView;     //代替標准的系統鍵盤        
@property (nullable, readwrite, strong) UIView *inputAccessoryView;  //編輯時顯示在系統鍵盤或用戶自定義的inputView上面的視圖

@property(nonatomic) BOOL clearsOnInsertion NS_AVAILABLE_IOS(6_0); // 默認值NO
@end

UITextField是繼承於UIControl,並且遵循NSCoding及UITextInput的協議;UITextInput的協議作用是用來輔助鍵盤輸入得協議,在需要用到鍵盤輸入得地方都需要實現這個協議;

知識點1:UITextBorderStyle的枚舉內容

typedef NS_ENUM(NSInteger, UITextBorderStyle) {
    UITextBorderStyleNone,/無任何邊框
    UITextBorderStyleLine,//黑色線框
    UITextBorderStyleBezel,//邊線+陰影
    UITextBorderStyleRoundedRect //淺色帶圓弧線框
};

知識點2:UITextFieldViewMode的枚舉內容

typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
    UITextFieldViewModeNever,//無清除按鈕
    UITextFieldViewModeWhileEditing,//編輯時出現清除按鈕
    UITextFieldViewModeUnlessEditing,//編輯時不出現,編輯後才出現清除按鈕
    UITextFieldViewModeAlways //一直顯示清除按鈕
};

知識點3:關於NSTextAlignment的說明,UITextAlignmentLeft (水平右對齊),UITextAlignmentCenter(水平居中對齊),UITextAlignmentRight (水平右對齊);

知識點4:修改UITextField中關於Placeholder的著色

[self.myTextField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];

當然也可以采用另外一種方式:

 NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]initWithString:@"水印提示文字"];
  [attrString addAttribute:NSForegroundColorAttributeNam
                     value:[UIColor redColor]
                     range:NSMakeRange(0, 2)];
  myTextFieldattributedPlaceholder =  attrString;

知識點5:關於leftView跟leftViewMode的運用

            _relayTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
            _relayTextField.backgroundColor = [UIColor whiteColor];
            _relayTextField.font = [UIFont fontWithName:@"OpenSans" size:15.0];
            _relayTextField.delegate = self;
            _relayTextField.layer.cornerRadius = 5.0f;
            _relayTextField.layer.masksToBounds = YES;
            _relayTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
            _relayTextField.autocorrectionType = UITextAutocorrectionTypeNo;
            _relayTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
            _relayTextField.returnKeyType=UIReturnKeySend;
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 70, 37)];
            label.font = [UIFont boldSystemFontOfSize:15];
            label.adjustsFontSizeToFitWidth = YES;
            label.textColor = COLOR_WORD_GRAY_2;
            _relayTextField.leftView = label;
            _relayTextField.leftViewMode = UITextFieldViewModeAlways;
            [self addSubview:_relayTextField];

設置顯示的值:

-(void)configuerWithName:(NSString*)name messageId:(NSString*)message_id
{
    _name = name;
    _messageId = message_id;
    if ([_relayTextField.leftView isKindOfClass:[UILabel class]]) {
        ((UILabel*)_relayTextField.leftView).text = [NSString stringWithFormat:@"回復%@ :",name];
        ((UILabel*)_relayTextField.leftView).textColor = COLOR_WORD_GRAY_2;
    }
}

知識點6:inputView跟inputAccessoryView 默認是系統的鍵盤,比如有自定義的鍵盤就可以把它賦值給inputView;當然也可以是其它效果的視圖,比如彈出選擇器等;實例如下:

//自定義鍵盤,將原有的鍵盤隱藏,顯示當前自定義視圖
UIView *keyBoardContent = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 100)];
keyBoardContent.backgroundColor = [UIColor darkGrayColor];
myTextField.inputView = keyBoardContent;


UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 80)];
subView.backgroundColor = [UIColor greenColor];
myTextField.inputAccessoryView = subView;

二:UITextInputTraits的相關內容,UITextField遵循這個協議,用來輔助鍵盤輸入得協議,在需要用到鍵盤輸入得地方都需要實現這個協議

@protocol UITextInputTraits <NSObject>

@optional

@property(nonatomic) UITextAutocapitalizationType autocapitalizationType; // default is UITextAutocapitalizationTypeSentences
@property(nonatomic) UITextAutocorrectionType autocorrectionType;         //是否糾錯 默認值 UITextAutocorrectionTypeDefault
@property(nonatomic) UITextSpellCheckingType spellCheckingType NS_AVAILABLE_IOS(5_0); // default is UITextSpellCheckingTypeDefault;
@property(nonatomic) UIKeyboardType keyboardType;                         // 鍵盤類型 默認值UIKeyboardTypeDefault
@property(nonatomic) UIKeyboardAppearance keyboardAppearance;             // 設定鍵盤顯示風格 默認值 UIKeyboardAppearanceDefault
@property(nonatomic) UIReturnKeyType returnKeyType;                       // default is UIReturnKeyDefault (See note under UIReturnKeyType enum)
@property(nonatomic) BOOL enablesReturnKeyAutomatically;                  // 設定當文本框沒有輸入內容時鍵盤得返回鍵是否可用@property(nonatomic,getter=isSecureTextEntry) BOOL secureTextEntry;       // 設定輸入文本是否要受到隱藏保護,默認為NO不保護,設定為YES,則文本輸入後為密碼風格得保護

@end

知識點7:secureTextEntry是設置是否顯示成密碼的形式,此屬性並不在UITextField裡面

知識點8:UIReturnKeyType(UITextInputTraits中)的枚舉內容如下

    UIReturnKeyDefault      ;//默認灰色按鈕,標有Return
    UIReturnKeyGo           ;//標有Go的藍色按鈕
    UIReturnKeyGoogle       ;//標有Google的藍色按鈕,用語搜索
    UIReturnKeyJoin         ;//標有Join的藍色按鈕
    UIReturnKeyNext         ;//標有Next的藍色按鈕
    UIReturnKeyRoute        ;//標有Route的藍色按鈕
    UIReturnKeySearch       ;//標有Search的藍色按鈕
    UIReturnKeySend         ;//標有Send的藍色按鈕
    UIReturnKeyYahoo        ;//標有Yahoo的藍色按鈕
    UIReturnKeyYahoo        ;//標有Yahoo的藍色按鈕
    UIReturnKeyEmergencyCall;//緊急呼叫按鈕

知識點9:autocapitalizationType(UITextInputTraits中)首字母是否大寫

    UITextAutocapitalizationTypeNone         ;//不自動大寫
    UITextAutocapitalizationTypeWords        ;//單詞首字母大寫
    UITextAutocapitalizationTypeSentences    ;//句子的首字母大寫
    UITextAutocapitalizationTypeAllCharacters;//所有字母都大寫

知識點10:keyboardAppearance(UITextInputTraits中)鍵盤外觀

   UIKeyboardAppearanceDefault ;//默認外觀,淺灰色
   UIKeyboardAppearanceAlert   ;//深灰石墨色

知識點11:autocorrectionType(UITextInputTraits中)是否糾錯

    UITextAutocorrectionTypeDefault ;   //默認
    UITextAutocorrectionTypeNo      ;   //不自動糾錯
    UITextAutocorrectionTypeYes     ;   //自動糾錯

知識點12:使文本框在界面打開時就獲取焦點,並彈出輸入鍵盤:[myTextField becomeFirstResponder]; 使文本框失去焦點,並收回鍵盤[myTextFieldresignfirstresponder]

鍵盤收起其它方式
//方式 1:
[[[UIApplication sharedApplication]keyWindow] endEditing:YES];
//方式 2:
[[UIApplication sharedApplication]sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
//方式 3:
[self.view endEditing:YES];

知識點13:因為UITextFiled是繼承於UIControl,所以它也是有增加事件addTaget的效果

[myTextField addTarget:self
          action:@selector(textFieldDidChange:)//私有方法
forControlEvents:UIControlEventEditingChanged];


- (void)textFieldDidChange:(UITextField*)textField{//類似UIButton addTag..監聽方法
    NSLog(@"輸入框內容 = %@",textField.text);
}

知識點14:關於UITextFiled的NotificaitonCenter監聽

      UITextFieldTextDidBeginEditingNotification  ;//監聽開始編輯
      UITextFieldTextDidChangeNotification        ;//監聽正在編輯
      UITextFieldTextDidEndEditingNotification    ;//監聽結束編輯
實例:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self
                   selector:@selector(texfFieldNotification:)
                       name:UITextFieldTextDidChangeNotification object:nil];

- (void)texfFieldNotification:(NSNotification*)noti{//私有方法
    NSLog(@"輸入款變化了");
}

當然記得在用後時移除通知;

知識點15:監聽鍵盤出現,知曉鍵盤CGRect

- (void)efObserverKeyBoardShowAndHidde{
    //注冊鍵盤出現
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyBoardWasShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyBoardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
- (void)keyBoardWasShow:(NSNotification*)aNotification{
    NSLog(@"鍵盤出現");
    //鍵盤高度
    //CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
}
-(void)keyBoardWillBeHidden:(NSNotification*)aNotification{
    NSLog(@"鍵盤消失");
}

- (void)removeObserver{//移除所有通知
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

三:UITextField定義的協議UITextFieldDelegate內容

@protocol UITextFieldDelegate <NSObject>

@optional

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;        // 返回一個BOOL值,指定是否循序文本字段開始編輯
- (void)textFieldDidBeginEditing:(UITextField *)textField;           // 開始編輯時觸發,獲得焦點時
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;          // 返回BOOL值,指定是否允許文本字段結束編輯,當編輯結束後
- (void)textFieldDidEndEditing:(UITextField *)textField;             // 結束編輯

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   // 用戶不段的輸入,可以控制達到某些條件,禁止輸入

- (BOOL)textFieldShouldClear:(UITextField *)textField;               // 返回一個BOOL值指明是否滿足什麼條件清除內容
- (BOOL)textFieldShouldReturn:(UITextField *)textField;              // 返回一個BOOL值,指明是否允許在按下回車鍵時結束編輯

@end

知識點1:運用實例

//限定輸入條件
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //得到輸入框的內容
    NSString * textString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if ([string isEqualToString:@"\n"]) {
        NSLog(@"回車");
    }
    if ([string isEqualToString:@""]) {
        NSLog(@"後退");
    }
    if ([string isEqualToString:@" "]) {
        NSLog(@"空格");
        //return NO;//禁止空格輸入
    }
    if (textString.length>4) {
        NSLog(@"輸入超過5位數");
    }
    //打印當前鍵盤輸入模式,en-US,zh-Hans....
    NSString *lang = [[UITextInputMode currentInputMode]primaryLanguage];

    //ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
    //限制輸入已知的字符
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789\n"]invertedSet];
    //按cs分離出數組,數組按@""分離出字符串
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; 
    BOOL canChange = [string isEqualToString:filtered];

    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{//辭去職務
    //主要是[receiver resignFirstResponder]在哪調用就能把receiver對應的鍵盤往下收
    [textField resignFirstResponder];
    return YES;
}

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