zoukankan      html  css  js  c++  java
  • 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了.

  • 相关阅读:
    从内存池到连接池 老码农眼中的资源池
    资源池(从内存池到连接池)
    资源池设计模式 (Resource Pool)和数据池的简单实现
    数据库连接池的工作原理
    原理 : 线程池、连接池、内存池
    聚簇索引与非聚簇索引(也叫二级索引)
    MyISAM 和 InnoDB 索引的区别
    MySQL 聚簇索引&&二级索引&&辅助索引
    关于如何提高Web服务端并发效率的异步编程技术
    为什么做java的web开发我们会使用struts2,springMVC和spring这样的框架?
  • 原文地址:https://www.cnblogs.com/iOS771722918/p/4479793.html
Copyright © 2011-2022 走看看