UIKit之UITextField篇

1.初始化控件 (文本輸入控件)

特殊初始化

 _evtxf = ({
        UITextField *ettxf = [[UITextField alloc]init];
        .
        .
        [self.view addSubview:ettxf];
        ettxf;
});

2.設(shè)置基本屬性及用法

frame:設(shè)置UITextField的顯示起點坐標(biāo)(x,y)和寬高(width,height)

 ettxf.frame = CGRectMake(<#x起點#>, <#y起點#>, <#寬度#>,<#高度#>);

placeholder:當(dāng)輸入框沒有內(nèi)容時,水印提示提示內(nèi)容為"水印提示"

ettxf.placeholder = @"水印提示";

//補充:設(shè)置placeholder的顏色枝哄,其中的_placeholderLabel.textColor是系統(tǒng)自帶的瓮钥,可以直接使用
[ettxf setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"]; 

//textColor:設(shè)置輸入文字字體顏色
ettxf.textColor = [UIColor redColor];
//設(shè)置光標(biāo)顏色  
[ettxf setTintColor:[UIColor whiteColor]];  

backgroundColor:設(shè)置輸入框的背景顏色招拙,此時設(shè)置為白色如果使用了自定義的背景圖片邊框會被忽略掉(建議:backgroundColor與background別同時使用)

ettxf.backgroundColor = [UIColor whiteColor];

background設(shè)置背景

ettxf.borderStyle = UITextBorderStyleNone;//先要去除邊框樣式(類似UIButtonCustom)
ettxf.background = [UIImage imageNamed:@"iconfont-Mask.png"];

font:設(shè)置輸入框內(nèi)容的字體樣式和大小

ettxf.font = [UIFont systemFontOfSize:15];

secureTextEntry:密碼形式輸入

ettxf.secureTextEntry = YES;

clearsOnBeginEditing:再次編輯就清空

ettxf.clearsOnBeginEditing = YES;

adjustsFontSizeToFitWidth:當(dāng)文字超出文本框?qū)挾葧r署照,自動調(diào)整文字大小

ettxf.adjustsFontSizeToFitWidth = YES;

minimumFontSize:最小可縮小的字號和adjustsFontSizeToFitWidth一起使用

ettxf.minimumFontSize = 20;

textAlignment:內(nèi)容對齊方式(水平對齊 )

ettxf.textAlignment = UITextAlignmentLeft;

contentVerticalAlignment: 垂直對齊 (該屬性不起作用禽作,待后續(xù)研究)

ettxf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

borderStyle:設(shè)置邊框樣式,只有設(shè)置了才會顯示邊框樣式

ettxf.borderStyle = UITextBorderStyleRoundedRect;

clearButtonMode:輸入框中是否有個叉號岸裙,在什么時候顯示,用于一次性刪除輸入框中的內(nèi)容

ettxf.clearButtonMode = UITextFieldViewModeAlways;

keyboardType:設(shè)置鍵盤的樣式

ettxf.keyboardType = UIKeyboardTypeDefault;

/************************************UIKeyboardType************************************/
        UIKeyboardTypeDefault           ;   //系統(tǒng)默認(rèn)的虛擬鍵盤
        UIKeyboardTypeASCIICapable      ;   //顯示英文字母的虛擬鍵盤
        UIKeyboardTypeNumbersAndPunctuation;//顯示數(shù)字+標(biāo)點的虛擬鍵盤
        UIKeyboardTypeURL               ;   //URL鍵盤速缆,支持.com按鈕只支持URL字符
        UIKeyboardTypeNumberPad         ;   //數(shù)字鍵盤
        UIKeyboardTypePhonePad          ;   //顯示便于撥號呼叫的電話鍵盤
        UIKeyboardTypeNamePhonePad      ;   //電話鍵盤降允,也支持輸入人名
        UIKeyboardTypeEmailAddress      ;   //用于輸入電子郵件地址的鍵盤
        UIKeyboardTypeDecimalPad        ;   //數(shù)字+小數(shù)點的數(shù)字鍵盤
        UIKeyboardTypeTwitter           ;   //優(yōu)化的鍵盤,方便輸入@艺糜、#字符
/**************************************************************************************/

autocorrectionType:是否糾錯

ettxf.autocorrectionType = UITextAutocorrectionTypeNo;

/***************************UITextAutocorrectionType***********************************/
        UITextAutocorrectionTypeDefault ;   //默認(rèn)
        UITextAutocorrectionTypeNo      ;   //不自動糾錯
        UITextAutocorrectionTypeYes     ;   //自動糾錯
/**************************************************************************************/

autocapitalizationType:首字母是否大寫

ettxf.autocapitalizationType = UITextAutocapitalizationTypeNone;

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

returnKeyType:return鍵變成什么鍵

ettxf.returnKeyType =UIReturnKeyDone;

/****************************UIReturnKeyType******************************************/
        UIReturnKeyDefault      ;//默認(rèn)灰色按鈕剧董,標(biāo)有Return
        UIReturnKeyGo           ;//標(biāo)有Go的藍(lán)色按鈕
        UIReturnKeyGoogle       ;//標(biāo)有Google的藍(lán)色按鈕,用語搜索
        UIReturnKeyJoin         ;//標(biāo)有Join的藍(lán)色按鈕
        UIReturnKeyNext         ;//標(biāo)有Next的藍(lán)色按鈕
        UIReturnKeyRoute        ;//標(biāo)有Route的藍(lán)色按鈕
        UIReturnKeySearch       ;//標(biāo)有Search的藍(lán)色按鈕
        UIReturnKeySend         ;//標(biāo)有Send的藍(lán)色按鈕
        UIReturnKeyYahoo        ;//標(biāo)有Yahoo的藍(lán)色按鈕
        UIReturnKeyYahoo        ;//標(biāo)有Yahoo的藍(lán)色按鈕
        UIReturnKeyEmergencyCall;//緊急呼叫按鈕
/**************************************************************************************/

leftView和leftViewMode:最右或者最左側(cè)(光標(biāo)前的占位符)

UIView *v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 2)];
v.backgroundColor = [UIColor redColor];
ettxf.leftView= v;
ettxf.leftViewMode = UITextFieldViewModeWhileEditing;

/**************************************************************************************/
        UITextFieldViewModeNever        ;//從不出現(xiàn)
        UITextFieldViewModeWhileEditing ;//當(dāng)編輯時出現(xiàn)
        UITextFieldViewModeUnlessEditing;//
        UITextFieldViewModeAlways       ;//一直存在
/**************************************************************************************/

keyboardAppearance:鍵盤外觀

ettxf.keyboardAppearance=UIKeyboardAppearanceDefault;

/****************************UIReturnKeyType*******************************************/
        UIKeyboardAppearanceDefault ;//默認(rèn)外觀破停,淺灰色
        UIKeyboardAppearanceAlert   ;//深灰石墨色
/**************************************************************************************/```

補充重點(addTaget:...)

[ettxf addTarget:self  action:@selector(<#方法名稱#>) forControlEvents:<#觸發(fā)狀態(tài)#>]

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

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

/****************************UIControlEvents********************************/
        UIControlEventEditingDidBegin      ;//
        UIControlEventEditingChanged       ;//
        UIControlEventEditingDidEnd        ;//
        UIControlEventEditingDidEndOnExit  ;//
/**************************************************************************

//補充重點(NotificaitonCenter監(jiān)聽)

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self
                   selector:@selector(texfFieldNotification:)
                       name:UITextFieldTextDidChangeNotification object:nil];

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

/***************************************************************************/
      UITextFieldTextDidBeginEditingNotification  ;//監(jiān)聽開始編輯
      UITextFieldTextDidChangeNotification        ;//監(jiān)聽正在編輯
      UITextFieldTextDidEndEditingNotification    ;//監(jiān)聽結(jié)束編輯
/***************************************************************************/

限制字符串輸出長度

[ettxf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

//這樣就可以更好地限制輸入長度:
- (void)textFieldDidChange:(UITextField *)textField {
    if (textField == self.titleField) {
        if (textField.text.length > 12) {
            textField.text = [textField.text substringToIndex:12];
        }
    }
}
  • 方法缺陷:對純字符的統(tǒng)計無影響翅楼,如果使用拼音輸入法時,方法的最后1個參數(shù)string接受的是輸入的字母真慢,而不是選擇的漢字毅臊,結(jié)果:當(dāng)想輸入文字“我愛你”,輸入拼音“woaini”黑界,每輸入一個字母便會進(jìn)入方法管嬉,統(tǒng)計的字符長度是字母的長度,實際上漢字還未超過限制長度朗鸠,但是字母的長度超過了導(dǎo)致無法繼續(xù)輸入

完美解決辦法:

- (void)textFieldDidChange:(UITextField *)textField {
    NSInteger kMaxLength = 12;
    NSString *toBeString = textField.text;
    NSString *lang = [[UIApplication sharedApplication] textInputMode].primaryLanguage; //ios7之前使用[UITextInputMode currentInputMode].primaryLanguage
    if ([lang isEqualToString:@"zh-Hans"]) { //中文輸入
        UITextRange *selectedRange = [textField markedTextRange];
        //獲取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        if (!position) {// 沒有高亮選擇的字蚯撩,則對已輸入的文字進(jìn)行字?jǐn)?shù)統(tǒng)計和限制
            if (toBeString.length > kMaxLength) {
                textField.text = [toBeString substringToIndex:kMaxLength];
            }
        } else{//有高亮選擇的字符串,則暫不對文字進(jìn)行統(tǒng)計和限制

        }
    } else {//中文輸入法以外的直接對其統(tǒng)計限制即可烛占,不考慮其他語種情況
        if (toBeString.length > kMaxLength) {
            textField.text = [toBeString substringToIndex:kMaxLength];
        }
    }
}

自定義鍵盤屬性(inputView)

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

ettxf.inputView = keyBoardContent;

自定義輔助鍵盤視圖(inputAccessoryView)

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

補充重點 (監(jiān)聽鍵盤出現(xiàn),知曉鍵盤CGRect)

- (void)efObserverKeyBoardShowAndHidde{
    //注冊鍵盤出現(xiàn)
    [[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(@"鍵盤出現(xiàn)");
    //鍵盤高度
    //CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
}
-(void)keyBoardWillBeHidden:(NSNotification*)aNotification{
    NSLog(@"鍵盤消失");
}

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

補充屬性(水印提示文字顏色)

attributedPlaceholder:水印提示文字顏色


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

3.代理協(xié)議及委托方法

用戶不段的輸入忆家,可以控制達(dá)到某些條件犹菇,禁止輸入(如,輸入手機號碼<=11位)*

//!!!!!!!!!!!!!!重點!!!!!!!!!!!!!!
//限定輸入條件
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //得到輸入框的內(nèi)容
    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位數(shù)");
    }

    //新思路-- xxx xxxx xxxx格式輸出手機號碼
      NSString * textString = [textField.text stringByReplacingCharactersInRange:range withString:string];
      if (textField == _phoneNumTFView.tf) {
          // 四位加一個空格
        if ([string isEqualToString:@""]) { // 刪除字符
                if (textString.length==4||textString.length==8) {
                    textField.text = [textField.text substringToIndex:textField.text.length - 1];
            }
        } else {
            //手機號輸入xxx xxxx xxxx
              if (textString.length==4||textString.length==9) {
                  textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
              }
        }
        return textString.length<=13;
    } 
    return YES;
}

4.鍵盤收起方式

方式 1:
[_evtxf  resignFirstResponder];
方式 2:
[[[UIApplication sharedApplication]keyWindow] endEditing:YES];
方式 3:
[[UIApplication sharedApplication]sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
方式 4:
[self.view endEditing:YES];

5.Block代替代理協(xié)議

1.使用方法

        //使用前提條件:導(dǎo)入UITextField+Blocks.h文件
        UITextField *ettxf = [[UITextField alloc]init];
        .
        .
        .
        ettxf.delegate = self;//設(shè)置代理

        //推薦使用方法:
        [ettxf setShouldBegindEditingBlock:^BOOL(UITextField *textField) {
            return YES;
        }];
        [ettxf setShouldChangeCharactersInRangeBlock:^BOOL(UITextField *textField, NSRange range, NSString *string) {
            NSString *str = [textField.text stringByReplacingCharactersInRange:range withString:string];
            NSLog(@"%@ || %@",string,str);
            return YES;
        }];
        [ettxf setShouldEndEditingBlock:^BOOL(UITextField *textField) {
            return YES;
        }];

        //與推薦方式一致:(不太理解block的弦赖,建議直接使用以上方法)
        ettxf.shouldBegindEditingBlock = ^BOOL(UITextField *textField){
            return YES;
        };
        
        ettxf.shouldEndEditingBlock = ^BOOL(UITextField *textField){
            return YES;
        };
        
        ettxf.shouldChangeCharactersInRangeBlock = ^BOOL(UITextField *textField, NSRange range, NSString *string){
            NSString *str = [textField.text stringByReplacingCharactersInRange:range withString:string];
            NSLog(@"%@ || %@",string,str);
            return YES;
        };
        [self.view addSubview:ettxf];

UITextField+Blocks.h文件

#import <UIKit/UIKit.h>

@interface UITextField (Blocks)

/**
 *  即將開始編輯
 */
@property (copy, nonatomic) BOOL (^shouldBegindEditingBlock)(UITextField *textField);
/**
 *  即將結(jié)束編輯
 */
@property (copy, nonatomic) BOOL (^shouldEndEditingBlock)(UITextField *textField);
/**
 *  已經(jīng)開始編輯
 */
@property (copy, nonatomic) void (^didBeginEditingBlock)(UITextField *textField);
/**
 *  已經(jīng)結(jié)束編輯
 */
@property (copy, nonatomic) void (^didEndEditingBlock)(UITextField *textField);
/**
 *  正在編輯中
 */
@property (copy, nonatomic) BOOL (^shouldChangeCharactersInRangeBlock)(UITextField *textField, NSRange range, NSString *replacementString);
/**
 *  即將點擊return
 */
@property (copy, nonatomic) BOOL (^shouldReturnBlock)(UITextField *textField);
/**
 *  即將點擊clearButton
 */
@property (copy, nonatomic) BOOL (^shouldClearBlock)(UITextField *textField);

- (void)setShouldBegindEditingBlock:(BOOL (^)(UITextField *textField))shouldBegindEditingBlock;
- (void)setShouldEndEditingBlock:(BOOL (^)(UITextField *textField))shouldEndEditingBlock;
- (void)setDidBeginEditingBlock:(void (^)(UITextField *textField))didBeginEditingBlock;
- (void)setDidEndEditingBlock:(void (^)(UITextField *textField))didEndEditingBlock;
- (void)setShouldChangeCharactersInRangeBlock:(BOOL (^)(UITextField *textField, NSRange range, NSString *string))shouldChangeCharactersInRangeBlock;
- (void)setShouldClearBlock:(BOOL (^)(UITextField *textField))shouldClearBlock;
- (void)setShouldReturnBlock:(BOOL (^)(UITextField *textField))shouldReturnBlock;

@end

UITextField+Blocks.m文件

#import "UITextField+Blocks.h"
#import <objc/runtime.h>

typedef BOOL (^UITextFieldReturnBlock) (UITextField *textField);
typedef void (^UITextFieldVoidBlock) (UITextField *textField);
typedef BOOL (^UITextFieldCharacterChangeBlock) (UITextField *textField, NSRange range, NSString *replacementString);

@implementation UITextField (Blocks)

static const void *UITextFieldDelegateKey = &UITextFieldDelegateKey;
static const void *UITextFieldShouldBeginEditingKey = &UITextFieldShouldBeginEditingKey;
static const void *UITextFieldShouldEndEditingKey = &UITextFieldShouldEndEditingKey;
static const void *UITextFieldDidBeginEditingKey = &UITextFieldDidBeginEditingKey;
static const void *UITextFieldDidEndEditingKey = &UITextFieldDidEndEditingKey;
static const void *UITextFieldShouldChangeCharactersInRangeKey = &UITextFieldShouldChangeCharactersInRangeKey;
static const void *UITextFieldShouldClearKey = &UITextFieldShouldClearKey;
static const void *UITextFieldShouldReturnKey = &UITextFieldShouldReturnKey;

#pragma mark UITextField Delegate methods
+ (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    UITextFieldReturnBlock block = textField.shouldBegindEditingBlock;
    if (block) {
        return block(textField);
    }
    id delegate = objc_getAssociatedObject(self, UITextFieldDelegateKey);
    if ([delegate respondsToSelector:@selector(textFieldShouldBeginEditing:)]) {
        return [delegate textFieldShouldBeginEditing:textField];
    }
    // return default value just in case
    return YES;
}
+ (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    UITextFieldReturnBlock block = textField.shouldEndEditingBlock;
    if (block) {
        return block(textField);
    }
    id delegate = objc_getAssociatedObject(self, UITextFieldDelegateKey);
    if ([delegate respondsToSelector:@selector(textFieldShouldEndEditing:)]) {
        return [delegate textFieldShouldEndEditing:textField];
    }
    // return default value just in case
    return YES;
}
+ (void)textFieldDidBeginEditing:(UITextField *)textField
{
    UITextFieldVoidBlock block = textField.didBeginEditingBlock;
    if (block) {
        block(textField);
    }
    id delegate = objc_getAssociatedObject(self, UITextFieldDelegateKey);
    if ([delegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) {
        [delegate textFieldDidBeginEditing:textField];
    }
}
+ (void)textFieldDidEndEditing:(UITextField *)textField
{
    UITextFieldVoidBlock block = textField.didEndEditingBlock;
    if (block) {
        block(textField);
    }
    id delegate = objc_getAssociatedObject(self, UITextFieldDelegateKey);
    if ([delegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
        [delegate textFieldDidBeginEditing:textField];
    }
}
+ (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    UITextFieldCharacterChangeBlock block = textField.shouldChangeCharactersInRangeBlock;
    if (block) {
        return block(textField,range,string);
    }
    id delegate = objc_getAssociatedObject(self, UITextFieldDelegateKey);
    if ([delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
        return [delegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
    }
    return YES;
}
+ (BOOL)textFieldShouldClear:(UITextField *)textField
{
    UITextFieldReturnBlock block = textField.shouldClearBlock;
    if (block) {
        return block(textField);
    }
    id delegate = objc_getAssociatedObject(self, UITextFieldDelegateKey);
    if ([delegate respondsToSelector:@selector(textFieldShouldClear:)]) {
        return [delegate textFieldShouldClear:textField];
    }
    return YES;
}
+ (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    UITextFieldReturnBlock block = textField.shouldReturnBlock;
    if (block) {
        return block(textField);
    }
    id delegate = objc_getAssociatedObject(self, UITextFieldDelegateKey);
    if ([delegate respondsToSelector:@selector(textFieldShouldReturn:)]) {
        return [delegate textFieldShouldReturn:textField];
    }
    return YES;
}
#pragma mark Block setting/getting methods
- (BOOL (^)(UITextField *))shouldBegindEditingBlock
{
    return objc_getAssociatedObject(self, UITextFieldShouldBeginEditingKey);
}
- (void)setShouldBegindEditingBlock:(BOOL (^)(UITextField *))shouldBegindEditingBlock
{
    [self setDelegateIfNoDelegateSet];
    objc_setAssociatedObject(self, UITextFieldShouldBeginEditingKey, shouldBegindEditingBlock, OBJC_ASSOCIATION_COPY);
}
- (BOOL (^)(UITextField *))shouldEndEditingBlock
{
    return objc_getAssociatedObject(self, UITextFieldShouldEndEditingKey);
}
- (void)setShouldEndEditingBlock:(BOOL (^)(UITextField *))shouldEndEditingBlock
{
    [self setDelegateIfNoDelegateSet];
    objc_setAssociatedObject(self, UITextFieldShouldEndEditingKey, shouldEndEditingBlock, OBJC_ASSOCIATION_COPY);
}
- (void (^)(UITextField *))didBeginEditingBlock
{
    return objc_getAssociatedObject(self, UITextFieldDidBeginEditingKey);
}
- (void)setDidBeginEditingBlock:(void (^)(UITextField *))didBeginEditingBlock
{
    [self setDelegateIfNoDelegateSet];
    objc_setAssociatedObject(self, UITextFieldDidBeginEditingKey, didBeginEditingBlock, OBJC_ASSOCIATION_COPY);
}
- (void (^)(UITextField *))didEndEditingBlock
{
    return objc_getAssociatedObject(self, UITextFieldDidEndEditingKey);
}
- (void)setDidEndEditingBlock:(void (^)(UITextField *))didEndEditingBlock
{
    [self setDelegateIfNoDelegateSet];
    objc_setAssociatedObject(self, UITextFieldDidEndEditingKey, didEndEditingBlock, OBJC_ASSOCIATION_COPY);
}
- (BOOL (^)(UITextField *, NSRange, NSString *))shouldChangeCharactersInRangeBlock
{
    return objc_getAssociatedObject(self, UITextFieldShouldChangeCharactersInRangeKey);
}
- (void)setShouldChangeCharactersInRangeBlock:(BOOL (^)(UITextField *, NSRange, NSString *))shouldChangeCharactersInRangeBlock
{
    [self setDelegateIfNoDelegateSet];
    objc_setAssociatedObject(self, UITextFieldShouldChangeCharactersInRangeKey, shouldChangeCharactersInRangeBlock, OBJC_ASSOCIATION_COPY);
}
- (BOOL (^)(UITextField *))shouldReturnBlock
{
    return objc_getAssociatedObject(self, UITextFieldShouldReturnKey);
}
- (void)setShouldReturnBlock:(BOOL (^)(UITextField *))shouldReturnBlock
{
    [self setDelegateIfNoDelegateSet];
    objc_setAssociatedObject(self, UITextFieldShouldReturnKey, shouldReturnBlock, OBJC_ASSOCIATION_COPY);
}
- (BOOL (^)(UITextField *))shouldClearBlock
{
    return objc_getAssociatedObject(self, UITextFieldShouldClearKey);
}
- (void)setShouldClearBlock:(BOOL (^)(UITextField *textField))shouldClearBlock
{
    [self setDelegateIfNoDelegateSet];
    objc_setAssociatedObject(self, UITextFieldShouldClearKey, shouldClearBlock, OBJC_ASSOCIATION_COPY);
}
#pragma mark control method
/*
 Setting itself as delegate if no other delegate has been set. This ensures the UITextField will use blocks if no delegate is set.
 */
- (void)setDelegateIfNoDelegateSet
{
    if (self.delegate != (id<UITextFieldDelegate>)[self class]) {
        objc_setAssociatedObject(self, UITextFieldDelegateKey, self.delegate, OBJC_ASSOCIATION_ASSIGN);
        self.delegate = (id<UITextFieldDelegate>)[self class];
    }
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末项栏,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子蹬竖,更是在濱河造成了極大的恐慌沼沈,老刑警劉巖流酬,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異列另,居然都是意外死亡芽腾,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進(jìn)店門页衙,熙熙樓的掌柜王于貴愁眉苦臉地迎上來摊滔,“玉大人,你說我怎么就攤上這事店乐〖杼桑” “怎么了?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵眨八,是天一觀的道長腺兴。 經(jīng)常有香客問我,道長廉侧,這世上最難降的妖魔是什么页响? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮段誊,結(jié)果婚禮上闰蚕,老公的妹妹穿的比我還像新娘。我一直安慰自己连舍,他們只是感情好没陡,可當(dāng)我...
    茶點故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著烟瞧,像睡著了一般诗鸭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上参滴,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天强岸,我揣著相機與錄音,去河邊找鬼砾赔。 笑死蝌箍,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的暴心。 我是一名探鬼主播妓盲,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼专普!你這毒婦竟也來了悯衬?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤檀夹,失蹤者是張志新(化名)和其女友劉穎筋粗,沒想到半個月后策橘,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡娜亿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年丽已,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片买决。...
    茶點故事閱讀 39,764評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡沛婴,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出督赤,到底是詐尸還是另有隱情嘁灯,我是刑警寧澤,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站怜庸,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜泥技,卻給世界環(huán)境...
    茶點故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望间驮。 院中可真熱鬧驾凶,春花似錦、人聲如沸滩褥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽瑰煎。三九已至铺然,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間酒甸,已是汗流浹背魄健。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留插勤,地道東北人沽瘦。 一個月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像农尖,于是被迫代替她去往敵國和親析恋。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內(nèi)容