• iOS&UITextView中的placeholder属性


    一看标题,就很屌丝!

    的确,系统不给咱们,那咱们就自己弄!

    具体步骤:

      1,创建一个类,继承UITextView.取名ZHHTextView;

      2,在drawRect:中实现placeholder,其中用到通知来监听text的change.

    大概的步骤就着两步,具体实现,看代码.<一行代码解千言>

    现在将.m文件代码公布如下:

    #import "ZHHTextView.h"

    @implementation ZHHTextView

    - (instancetype)initWithFrame:(CGRect)frame {

        if (self = [super initWithFrame:frame]) {

            NSLog(@"%s",__func__);

            //注册通知.要用到通知的用意:监听内容的变化

            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewTextChange) name:UITextViewTextDidChangeNotification object:nil];

        }

        return self;

    }

    - (void)viewTextChange {

        // 执行此方法,系统自动调用drawRect:方法

        [self setNeedsDisplay];

        

        NSLog(@"%s",__func__);

        

    }

    - (void)dealloc {

        //取消通知,你不取消试试,看你的项目会不会崩

        [[NSNotificationCenter defaultCenter] removeObserver:self];

    }

    // Only override drawRect: if you perform custom drawing.

    // An empty implementation adversely affects performance during animation.

    - (void)drawRect:(CGRect)rect {

        // Drawing code

        

        // 如果有内容,则返回

        if (self.hasText)return;

        

        // 给placeholder添加属性

        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];

        //这里最好还是要与self.font同步

        attributes[NSFontAttributeName] = [UIFont systemFontOfSize:15.0];

        attributes[NSForegroundColorAttributeName] = [UIColor grayColor];

        

        // 其实placeholder是画上去的,既然是画上去的,必须给定具体的位置与尺寸

        CGFloat x = 15;

        CGFloat w = rect.size.width - 2 * x;

        CGFloat y = 12;

        CGFloat h = rect.size.height - 2 * y;

        CGRect placeholderRect = CGRectMake(x, y, w, h);

        NSString* placeholder = @"请输入鸿歌的QQ...";

     // 这个方法很经典

        [placeholder drawInRect:placeholderRect withAttributes:attributes];

    }

    @end

    OK了.

  • 相关阅读:
    前端错误监控上报公共方法,可在父页面及iframe子页面同时使用
    python3.7爬取墨菲定律保存在本地txt
    实现一个左滑删除功能
    用docsify快速构建文档,并用GitHub Pages展示
    最常用的快捷键总结
    有价值的帖子或博客链接
    解决8080端口占用问题
    用gulp构建你的前端项目
    移动端右侧栏导航面板
    自己封装一个弹框插件
  • 原文地址:https://www.cnblogs.com/iOS771722918/p/4479793.html
Copyright © 2020-2023  润新知