天生不是作曲家UI基础iOS开发专题

UIKit之UITextField篇

2016-03-04  本文已影响527人  陈胜华

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

特殊初始化

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

2.设置基本属性及用法

frame:设置UITextField的显示起点坐标(x,y)和宽高(width,height)

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

placeholder:当输入框没有内容时,水印提示提示内容为"水印提示"

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

//补充:设置placeholder的颜色,其中的_placeholderLabel.textColor是系统自带的,可以直接使用
[ettxf setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"]; 

//textColor:设置输入文字字体颜色
ettxf.textColor = [UIColor redColor];
//设置光标颜色  
[ettxf setTintColor:[UIColor whiteColor]];  

backgroundColor:设置输入框的背景颜色,此时设置为白色如果使用了自定义的背景图片边框会被忽略掉(建议:backgroundColor与background别同时使用)

ettxf.backgroundColor = [UIColor whiteColor];

background设置背景

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

font:设置输入框内容的字体样式和大小

ettxf.font = [UIFont systemFontOfSize:15];

secureTextEntry:密码形式输入

ettxf.secureTextEntry = YES;

clearsOnBeginEditing:再次编辑就清空

ettxf.clearsOnBeginEditing = YES;

adjustsFontSizeToFitWidth:当文字超出文本框宽度时,自动调整文字大小

ettxf.adjustsFontSizeToFitWidth = YES;

minimumFontSize:最小可缩小的字号和adjustsFontSizeToFitWidth一起使用

ettxf.minimumFontSize = 20;

textAlignment:内容对齐方式(水平对齐 )

ettxf.textAlignment = UITextAlignmentLeft;

contentVerticalAlignment: 垂直对齐 (该属性不起作用,待后续研究)

ettxf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

borderStyle:设置边框样式,只有设置了才会显示边框样式

ettxf.borderStyle = UITextBorderStyleRoundedRect;

clearButtonMode:输入框中是否有个叉号,在什么时候显示,用于一次性删除输入框中的内容

ettxf.clearButtonMode = UITextFieldViewModeAlways;

keyboardType:设置键盘的样式

ettxf.keyboardType = UIKeyboardTypeDefault;

/************************************UIKeyboardType************************************/
        UIKeyboardTypeDefault           ;   //系统默认的虚拟键盘
        UIKeyboardTypeASCIICapable      ;   //显示英文字母的虚拟键盘
        UIKeyboardTypeNumbersAndPunctuation;//显示数字+标点的虚拟键盘
        UIKeyboardTypeURL               ;   //URL键盘,支持.com按钮只支持URL字符
        UIKeyboardTypeNumberPad         ;   //数字键盘
        UIKeyboardTypePhonePad          ;   //显示便于拨号呼叫的电话键盘
        UIKeyboardTypeNamePhonePad      ;   //电话键盘,也支持输入人名
        UIKeyboardTypeEmailAddress      ;   //用于输入电子邮件地址的键盘
        UIKeyboardTypeDecimalPad        ;   //数字+小数点的数字键盘
        UIKeyboardTypeTwitter           ;   //优化的键盘,方便输入@、#字符
/**************************************************************************************/

autocorrectionType:是否纠错

ettxf.autocorrectionType = UITextAutocorrectionTypeNo;

/***************************UITextAutocorrectionType***********************************/
        UITextAutocorrectionTypeDefault ;   //默认
        UITextAutocorrectionTypeNo      ;   //不自动纠错
        UITextAutocorrectionTypeYes     ;   //自动纠错
/**************************************************************************************/

autocapitalizationType:首字母是否大写

ettxf.autocapitalizationType = UITextAutocapitalizationTypeNone;

/***************************UITextAutocapitalizationType******************************/
        UITextAutocapitalizationTypeNone         ;//不自动大写
        UITextAutocapitalizationTypeWords        ;//单词首字母大写
        UITextAutocapitalizationTypeSentences    ;//句子的首字母大写
        UITextAutocapitalizationTypeAllCharacters;//所有字母都大写
/**************************************************************************************/

returnKeyType:return键变成什么键

ettxf.returnKeyType =UIReturnKeyDone;

/****************************UIReturnKeyType******************************************/
        UIReturnKeyDefault      ;//默认灰色按钮,标有Return
        UIReturnKeyGo           ;//标有Go的蓝色按钮
        UIReturnKeyGoogle       ;//标有Google的蓝色按钮,用语搜索
        UIReturnKeyJoin         ;//标有Join的蓝色按钮
        UIReturnKeyNext         ;//标有Next的蓝色按钮
        UIReturnKeyRoute        ;//标有Route的蓝色按钮
        UIReturnKeySearch       ;//标有Search的蓝色按钮
        UIReturnKeySend         ;//标有Send的蓝色按钮
        UIReturnKeyYahoo        ;//标有Yahoo的蓝色按钮
        UIReturnKeyYahoo        ;//标有Yahoo的蓝色按钮
        UIReturnKeyEmergencyCall;//紧急呼叫按钮
/**************************************************************************************/

leftView和leftViewMode:最右或者最左侧(光标前的占位符)

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

/**************************************************************************************/
        UITextFieldViewModeNever        ;//从不出现
        UITextFieldViewModeWhileEditing ;//当编辑时出现
        UITextFieldViewModeUnlessEditing;//
        UITextFieldViewModeAlways       ;//一直存在
/**************************************************************************************/

keyboardAppearance:键盘外观

ettxf.keyboardAppearance=UIKeyboardAppearanceDefault;

/****************************UIReturnKeyType*******************************************/
        UIKeyboardAppearanceDefault ;//默认外观,浅灰色
        UIKeyboardAppearanceAlert   ;//深灰石墨色
/**************************************************************************************/```

补充重点(addTaget:...)

[ettxf addTarget:self  action:@selector(<#方法名称#>) forControlEvents:<#触发状态#>]

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

- (void)textFieldDidChange:(UITextField*)textField{//类似UIButton addTag..监听方法
    NSLog(@"输入框内容 = %@",textField.text);
}

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

//补充重点(NotificaitonCenter监听)

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

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

/***************************************************************************/
      UITextFieldTextDidBeginEditingNotification  ;//监听开始编辑
      UITextFieldTextDidChangeNotification        ;//监听正在编辑
      UITextFieldTextDidEndEditingNotification    ;//监听结束编辑
/***************************************************************************/

自定义键盘属性(inputView)

//自定义键盘,将原有的键盘隐藏,显示当前自定义视图
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;

补充重点 (监听键盘出现,知晓键盘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];
}

补充属性(水印提示文字颜色)

attributedPlaceholder:水印提示文字颜色


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

3.代理协议及委托方法

用户不段的输入,可以控制达到某些条件,禁止输入(如,输入手机号码<=11位)*

//!!!!!!!!!!!!!!重点!!!!!!!!!!!!!!
//限定输入条件
- (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位数");
    }

    //新思路-- 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代替代理协议

1.使用方法

        //使用前提条件:导入UITextField+Blocks.h文件
        UITextField *ettxf = [[UITextField alloc]init];
        .
        .
        .
        ettxf.delegate = self;//设置代理

        //推荐使用方法:
        [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);
/**
 *  即将结束编辑
 */
@property (copy, nonatomic) BOOL (^shouldEndEditingBlock)(UITextField *textField);
/**
 *  已经开始编辑
 */
@property (copy, nonatomic) void (^didBeginEditingBlock)(UITextField *textField);
/**
 *  已经结束编辑
 */
@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
上一篇下一篇

猜你喜欢

热点阅读