zoukankan      html  css  js  c++  java
  • 用一个案列详细讲解UITextFiled

    一. 登陆界面的搭建

    首先涉及到登录界面状态栏颜色的问题,我们需要将状态栏颜色改为白色,可以在控制器内实现方法更改

    - (UIStatusBarStyle)preferredStatusBarStyle
    {
        return UIStatusBarStyleLightContent;
    }

    关于修改状态栏颜色更详细的介绍可以去看状态栏的管理

    因为登陆界面很多地方都需要用到,例如查看关注时需要登陆,添加关注时也需要先登录,发表新帖时也要登陆,登录界面不属于任何一个模块,同时很多地方也要用到它,所以将它写在Other文件夹中,另外登录界面一定是Mode出来的,一旦判断需要登录才可以进行操作就Mode出登录界面。

    通过观察登录界面,我们发现背景图片是提供好的,因此需要使用UIImageVIew设置背景图片,另外可以将登陆界面分为三部分,每一部分用UIView当载体存放,只要View内部的控件布局好了,只需要管理三个View的位置大小几个,方便于我们布局和管理。

    1. 快速登录按钮的布局

    首先快速登录方便的两条线都是图片,只需要简单设置frame即可,下面的三个快速登录明显是按钮,但是我们知道,UIButton默认的是UIImage在左边,titleLabel在右边,那么我们需要使默认的布局改为UIImage在上面,titleLabel在下面。

    方法一:可以通过设置UIImage和titleLabel的contentInset调整他们的位置,但是这种方法十分繁琐,需要我们耗费很长时间去慢慢调整,contentInset一般用在简单修改控件内内容位置。不建议在这里使用。

    方法二:自定义button 并且重写layoutSubviews。如果button是从storyboard或者xib加载会调用aweakfromnib方法,我们可以在aweakFromNib中对控件进行一些统一的设置,在layoutSubviews中设置控件内内容的位置。

    -(void)awakeFromNib
    {
        [super awakeFromNib];
        // 可以在这里对button进行一些统一的设置   文字居中
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    -(void)layoutSubviews
    {
        [super layoutSubviews];
        // 修改imageView和titleLabel的位置
        self.imageView.cl_y = 0;
        self.imageView.cl_centerX = self.cl_width*0.5;
        self.titleLabel.cl_x = 0;
        self.titleLabel.cl_width = self.cl_width;
        self.titleLabel.cl_y = self.imageView.cl_height;
        self.titleLabel.cl_height = self.cl_height - self.imageView.cl_height;
    }

    注意:一定要记得调用父类的对应的方法。

    关于三个button添加约束的方法:可以先设置中间按钮约束,然后约束三个按钮相互之间的间距为0。左边按钮与屏幕左边间距为0,右边按钮与屏幕右边为0,高度相同。最后约束三个按钮平分屏幕宽度。

    关于添加约束的方法有很多种,只要确定控件位置宽高就可以约束成功,需要细心一步一步来,即使约束失败也没有关系,删了重新约束即可,只要多试几次慢慢就会掌握。

    2. ❌号和注册账号布局

    第一部分的布局非常简单,这里有一个注意点:UIButton 当只有一张图片显示的时候 ,建议使用image而不要设置背景图片,因为背景图片的设置会看按钮有多大就将图片拉伸到大,图片会被拉伸。当设置image时图片不会变形,并且可以放大按钮的点击范围。所以这里的❌号选择设置UIButton的image,而不是backgroundImage。

    3. 账号密码输入框登录按钮布局

    这部分的布局也很简单,这里图片中提供了textfield的背景图片,所以这里我们先用UIImageView将背景图片显示,然后在在图片上添加一个透明的textfield,所以textfield的样式需要选择无边框隐形的

    另外登陆按钮需要设置Type为Custom,如果是System当我们按下的时候会自动做出处理如下图,并且会自动将字体渲染成蓝色

    设置为Custom就会在高亮时显示我们设置的背景图片,并且不会渲染字体颜色。

    设置button按钮的圆角

    self.loginBtn.layer.cornerRadius = 5;
    self.loginBtn.layer.masksToBounds = YES;

    也可以通过KVC赋值来设置

    [self.loginBtn setValue:@5 forKeyPath:@"layer.cornerRadius"];
    [self.loginBtn setValue:@YES forKeyPath:@"layer.masksToBunds"];

    当然在xib中也可以通过KVC来赋值

    因为需要已有账号和注册账号两个界面的切换的动画效果,所以将两个两个输入界面拼接起来,如图所示

    登录注册拼接

    如果想点击button实现动画,我们需要修改view左边线与左边屏幕的约束,获得约束属性,将View左边线与屏幕左边的距离从0修改为负一个屏幕宽度,当然也需要添加登陆View右边线和注册View左边线距离为0。同时修改button的title。

    - (IBAction)showLogionOrRegister:(UIButton *)sender {
        [self.view endEditing:YES];
        if (self.leftMargin.constant) {
            self.leftMargin.constant = 0;
            [sender setTitle:@"注册账号" forState:UIControlStateNormal];
        }else{
            self.leftMargin.constant = -self.view.cl_width;
            [sender setTitle:@"已有账号?" forState:UIControlStateNormal];
        }
        [UIView animateWithDuration:0.5 animations:^{
            [self.view layoutIfNeeded];
        }];
    }

    这里难点在于约束的添加和修改自己细心修改就会成功,当然也可以通过代码修改两个View的frame来达到动画替换效果。

    4. textfield光标颜色的改变和占位文字颜色改变

    首先,这里有四个textfield,每一个都需要设置光标颜色和占位文字颜色,所以我们通过自定义textfield来实现,然后再awakeFromNib中设置一次就可以。
    textfield的光标的颜色我们可以通过设置tintColor来设置

    self.tintColor = [UIColor whiteColor];

    占位文字的颜色修改

    方法一:使用富文本修改占位文字颜色

    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[NSForegroundColorAttributeName] = [UIColor whiteColor];
    self.attributedPlaceholder = [[NSAttributedString alloc]initWithString:self.placeholder attributes:attributes];

    方法二:通过重写drawRect方法来重绘站位文字并修改站位文字颜色

    -(void)drawPlaceholderInRect:(CGRect)rect
    {
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[NSFontAttributeName] = self.font;
        attributes[NSForegroundColorAttributeName] = [UIColor whiteColor];
        // 从一个起点开始绘画
        CGPoint placeholderPoint = CGPointMake(0, (self.cl_height - self.font.lineHeight)*0.5);
        [self.placeholder drawAtPoint:placeholderPoint withAttributes:attributes];
        // 画到一个范围
    //    self.placeholder drawInRect:<#(CGRect)#> withAttributes:<#(nullable NSDictionary<NSString *,id> *)#>
    }

    方法三:直接修改内部占位文字Label的文字颜色

    其实textfield内部有一个placeholderLabel,用来显示占位文字。我们可以通过图形化调试工具中看到textfield内部结构

    //    UILabel *label = [self valueForKeyPath:@"placeholderLabel"];
    //    label.textColor = [UIColor whiteColor];
    // 或者直接设置颜色    
     [self setValue:[UIColor grayColor] forKeyPath:@"placeholderLabel.textColor"];

    我们可以通过RunTime找到textfield内部有placeholderLabel私有属性

    //先使用运行时找到私有属性
    unsigned int count;
    Ivar *ivarList = class_copyIvarList([UITextField class], &count);
    for (int i = 0; i < count; i ++) {
        Ivar ivar = ivarList[i];
        NSLog(@"%s",ivar_getName(ivar));
    }
    free(ivarList);

    使用运行时打印textfield的全部属性,我们可以找到placeholderLabel

    5. 切换占位文字颜色颜色

    当textfield处于未编辑状态时,占位文字颜色为灰色,当textfield处于编辑状态时,占位文字颜色为白色

    方法一:addTarget

    因为textfield继承于UIControl,所以可以使用addTarget监听textfield编辑状态的改变

    [self addTarget:self action:@selector(editingDidBegin) forControlEvents:UIControlEventEditingDidBegin];
    [self addTarget:self action:@selector(editingDidEnd) forControlEvents:UIControlEventEditingDidEnd];

    然后在方法中修改占位文字颜色

    -(void)editingDidBegin
    {
    [self setValue:[UIColor whiteColor] forKeyPath:@"placeholderLabel.textColor"];
    }
    -(void)editingDidEnd
    {
    [self setValue:[UIColor grayColor] forKeyPath:@"placeholderLabel.textColor"];
    }

    方法二:使用代理

    使用代理是有风险的,当我们在控制器中再次设置textfield的代理的时候就会发生错误

    textField.delegate = self;
    #pragma mark - <UITextFieldDelegate>
    - (void)textFieldDidBeginEditing:(UITextField *)textField
    {
    //开始编辑时
    }
    - (void)textFieldDidEndEditing:(UITextField *)textField
    {
    // 结束编辑时
    }

    方法三:使用通知

    // object:self对象发出UITextFieldTextDidBeginEditingNotification通知就调用 self(监听器)的editingDidBegin方法
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(editingDidBegin) name:UITextFieldTextDidBeginEditingNotification object:self];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(editingDidEnd) name:UITextFieldTextDidEndEditingNotification object:self];

    通知还有一种方法,可直接在block中写要执行的操作

    // object:self对象发出名字为name的通知,就执行block里面的代码,可以修改block执行的线程,需要保存返回值,等不用的时候释放
    self.observer = [[NSNotificationCenter defaultCenter]addObserverForName:UITextFieldTextDidBeginEditingNotification object:self queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        // 监听到通知执行操作
    }];

    通知需要移除

    -(void)dealloc
    {
        [[NSNotificationCenter defaultCenter]removeObserver:self];
        // 使用block处理监听方法时移除监听
       [[NSNotificationCenter defaultCenter]removeObserver:self.observer];
    }
    
    方法四:重写UITextField的 becomeFirstResponder 和 resignFirstResponder 方法
    
    //调用时刻 : 成为第一响应者(开始编辑弹出键盘获得焦点)
    - (BOOL)becomeFirstResponder
    {
        return [super becomeFirstResponder];
    }
    //调用时刻 : 不做第一响应者(结束编辑退出键盘失去焦点)
    - (BOOL)resignFirstResponder
    {
        return [super resignFirstResponder];
    }

    6. 一些事件的添加和实现

    至此,界面已经基本布局完成,接下来就是给按钮添加点击事件。

    点击❌号按钮dismiss登录界面

    // 关闭按钮点击事件
    - (IBAction)closeBtn {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    点击空白区域使textfield退出第一响应者
    
    // 空白区域点击也关闭
    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        [self.view endEditing:YES];
    }

    三. 方法的抽取和一些知识点总结

    1.uitextfield添加分类,直接修改站位文字颜色。

    之前提到,为了避免重复多次的给textfield设置光标颜色和占位文字颜色,我们使用自定义textfield,在awakeFromNib中统一设置即可。另外设置占位文字颜色,以后再其他模块中或者其他项目中都有可能频繁使用,因此给textfield添加分类,使占位文字的设置更加方便。

    #import "UITextField+CLExtension.h"
    
    static NSString * const CLPlaceholderColorKey = @"placeholderLabel.textColor";
    @implementation UITextField (CLExtension)
    
    -(void)setPlaceholderColor:(UIColor *)placeholderColor
    {
        // 提前设置占位文字,让他提前创建placeholderLabel 需要有一个空格,不然起不到作用
        // 防止我们在外面使用的时候 先设置占位文字图片,在设置占位文字。导致占位文字颜色设置失败
        // 需要判断placeholder是否有值,如果没有我们才需要提前去创建 
       // 我们可以先保留现在的placeholder,当现在的为空的时候,我们先将他保存起来,然后设置为@" ",这时占位文字的颜色也会设置,然后在将占位文字的内容修改回为空,此时即使我们只设置了占位文字颜色,没有设置占位文字,打印占位文字为null
    //    NSString *oldplaceholder = self.placeholder;
    //    self.placeholder = @" ";
    //    self.placeholder = oldplaceholder;
    // 只有一开始为空的时候才需要先创建placeholderLabel
        if (self.placeholder.length == 0) {
            self.placeholder = @" ";
            self.placeholder = nil;
        }
        // 恢复到默认颜色
        if (placeholderColor == nil) {
           // 系统默认颜色GRB值
            placeholderColor = [UIColor colorWithRed:0 green:0 blue:0.0980392 alpha:0.22];
        }
        [self setValue:placeholderColor forKeyPath:CLPlaceholderColorKey]; 
    }
    -(UIColor *)placeholderColor
    {
        return [self valueForKeyPath:CLPlaceholderColorKey];
    }

    此时我们设置占位文字颜色的时候就非常简单了

    //系统设置光标颜色与我们的分类做对比
    // textfield.tintColor = [UIColor whiteColor];
    textfield.placeholderColor = [UIColor grayColor];

    2.一些知识点补充

    frame 和 bounds的区别

    首先我们需要明白每一个控件都由矩形框和内容组成。默认情况下矩形框和内容是重合的

    frame
        以父控件 内容的左上角为坐标原点, 计算出的控件自己 矩形框的位置和尺寸
    bounds
        以控件自己 内容的左上角为坐标原点, 计算出的控件自己 矩形框的位置和尺寸

    NSAttributensstring和NSMutableAttributensstring的简单实用
    NSAttributensstring 带有属性的字符串 继承 NSObject,由两部分组成

    文字内容 : nsstring
    
    文字属性 :
        文字颜色 NSForegroundColorAttributeName
        字体大小 NSFontAttributeName
        下划线 NSUnderlineStyleAttributeName
        背景颜色 NSBackgroundColorAttributeName
    
    // 带有属性的文字内容
    @property(nullable, nonatomic,copy)   NSAttributedString     *attributedPlaceholder
    
    // 字典初始化
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[NSForegroundColorAttributeName] = [UIColor darkGrayColor];
    
    // 初始化
    textfield.attributedPlaceholder = [[NSAttributedString alloc]initWithString:self.placeholder attributes:attributes];
    
    NSMutableAttributensstring 继承自 NSAttributensstring
    
    NSMutableAttributensstring常见方法
    
    // 设置range范围的属性, 重复设置同一个范围的属性, 最后一次设置才是有效的(之前的设置会被覆盖掉)
    - (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
    
    // 添加range范围的属性, 同一个范围, 可以不断累加属性
    - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
    - (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;

    一般只要牵扯到显示文字的地方都可以使用富文本来做一些显示的优化,下面我们来看一些使用的实例

    图文混排

    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(100, 100, 200, 25);
    label.backgroundColor = [UIColor redColor];
    label.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:label];
    
    // 图文混排
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
    // 1 - 图片前部分
    NSAttributedString *first = [[NSAttributedString alloc] initWithString:@"你好"];
    [attributedText appendAttributedString:first];
    
    // 2 - 图片
    // 带有图片的附件对象
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:@"header_cry_icon"];
    CGFloat lineH = label.font.lineHeight;
    attachment.bounds = CGRectMake(0, - ((label.xmg_height - lineH) * 0.5 - 1), lineH, lineH);
    // 将附件对象包装成一个属性文字
    NSAttributedString *second = [NSAttributedString attributedStringWithAttachment:attachment];
    [attributedText appendAttributedString:second];
    
    // 3 - 图片后部分
    NSAttributedString *third = [[NSAttributedString alloc] initWithString:@"哈哈哈"];
    [attributedText appendAttributedString:third];
    
    label.attributedText = attributedText;

    一个Label显示多行不同字体的文字

    UILabel *label = [[UILabel alloc] init];
    // 设置属性文字
    NSString *text = @"你好
    哈哈哈";
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
    [attributedText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, text.length)];
    [attributedText addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(3, 3)];
    label.attributedText = attributedText;
    // 其他设置
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    label.frame = CGRectMake(0, 0, 100, 40);
    [self.view addSubview:label];
    self.navigationItem.titleView = label;

    四. 总结

    今天的任务已经完成,我们完成了关注和登陆界面的搭建,对登录界面做了一些细节处理,第二天效果如下

    今天的主要内容是对textfield的一些处理,关注textfield更多详细的知识可以去看iOS-UITextField 全面解析

  • 相关阅读:
    fiddler模拟弱网测试环境
    3.12 获取地址定位
    3.11 第一次个人作业7
    3.10 第一次个人作业6
    3.9 第一次个人作业5
    3.8 第一次个人作业4
    3.7 第一个次个人作业3
    3.6 第一次个人作业2
    3.5 第一次个人作业
    3.4 TextClock的基本使用
  • 原文地址:https://www.cnblogs.com/pioneerMax/p/5965290.html
Copyright © 2011-2022 走看看