zoukankan      html  css  js  c++  java
  • 你真的了解UITextField吗?

    一:首先查看一下关于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的协议作用是用来辅助键盘输入得协议,在需要用到键盘输入得地方都需要实现这个协议;

    知识点1UITextBorderStyle的枚举内容

    typedef NS_ENUM(NSInteger, UITextBorderStyle) {
        UITextBorderStyleNone,/无任何边框
        UITextBorderStyleLine,//黑色线框
        UITextBorderStyleBezel,//边线+阴影
        UITextBorderStyleRoundedRect //浅色带圆弧线框
    };

    知识点2UITextFieldViewMode的枚举内容

    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;
        }
    }

    知识点6inputView跟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里面

    知识点8UIReturnKeyType(UITextInputTraits中)的枚举内容如下

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

    知识点9autocapitalizationType(UITextInputTraits中)首字母是否大写

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

    知识点10keyboardAppearance(UITextInputTraits中)键盘外观

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

    知识点11autocorrectionType(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:@"
    "]) {
            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
    "]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;
    }

     

  • 相关阅读:
    js如何获取当天日期的开始时间和结束时间
    bootstrapTable 刷新数据
    vue全家桶
    JavaScript数组是否存在及是否存在某个元素
    asp.net core 负载均衡集群搭建(centos7+nginx+supervisor+kestrel)
    (转) 将ASP.NET Core应用程序部署至生产环境中(CentOS7)
    mysql 5.7 docker 主从复制架构搭建
    CentOS6.x生产环境下一键安装mono+jexus的脚本,自启动,带服务,版本号自控
    使用 Json.Net 对Json文本进行 增删改查
    C# dynamic 动态创建 json
  • 原文地址:https://www.cnblogs.com/wujy/p/5807073.html
Copyright © 2011-2022 走看看