码迷,mamicode.com
首页 > 其他好文 > 详细

新浪微博客户端(36)-自定义带placeholder的TextView

时间:2016-11-24 21:43:50      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:dea   注册   instance   请求   attr   注意   idc   客户端   操作   

iOS 上自带的UITextView竟然不能设置placeholder,但是UITextView却可以,我也真是醉了。没办法了,自己写一个

DJTextView.h

#import <UIKit/UIKit.h>

@interface DJTextView : UITextView


@property (nonatomic,copy) NSString *placeholder;
@property (nonatomic,strong) UIColor *placeholderColor;


@end

 

DJTextView.m

#import "DJTextView.h"

@implementation DJTextView




- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 在通知中心为TextView注册一个当文本改变的通知,当文本发生变化时,TextView会发一个通知
        // 类似于android里面的BroadcastReceiver
        // iOS 注册接收通知的方式为:addObserver name:
        // android 注册接收通知的方式为:intent.addAction();
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textHasChange) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}



// 当文字改变时会调用此方法
- (void)textHasChange {

    // setNeedsDisplay 类似于android里面的postInvalidate()方法,都是向操作系统发出请求重绘的消息
    // 操作系统会在未来的时间内调用drawRect(iOS),onDraw(android);
    // 注意:系统不允许我们自己调用drawRect或onDraw方法
    [self setNeedsDisplay];

}



- (void)drawRect:(CGRect)rect {

    
    if ([self hasText]) return; // 如果检测到当前TextView中有文本,就不再绘制
    
    CGFloat placeholderRectX = 5;
    CGFloat placeholderRectY = 8;
    CGFloat placeholderRectW = rect.size.width - 2 * placeholderRectX;
    CGFloat placeholderRectH = rect.size.height - 2 * placeholderRectY;
    
    
    // 将文本绘制在一个指定的矩形框内
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = self.font;
    attrs[NSForegroundColorAttributeName] = self.placeholderColor;
    
    [self.placeholder drawInRect:CGRectMake(placeholderRectX, placeholderRectY, placeholderRectW, placeholderRectH) withAttributes:attrs];
    

}


- (void)dealloc {

        // 类似于android,通知中心在使用完毕后需要销毁
        // iOS: [NSNotificationCenter defaultCenter] removeObserver:self]
        // android: unRegister(mBroadcastReceiver);
       [[NSNotificationCenter defaultCenter] removeObserver:self];

}



@end

最终效果:

技术分享

 

新浪微博客户端(36)-自定义带placeholder的TextView

标签:dea   注册   instance   请求   attr   注意   idc   客户端   操作   

原文地址:http://www.cnblogs.com/yongdaimi/p/6099498.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!