UITextView自定义placeholder

UITextView自定义placeholder

来自我独立博客 先来吐槽一下本身, 博客建起来差很少已经一个月了, 第一篇文章都一拖再拖, 实在对不起这优秀的typecho. 为了这博客不要还没写起来就荒废, 决定之后一个星期最少一个文章. 第一篇就以简单的开始吧.ios

使用UITextView常常会须要用到placeholder, 惋惜UITextView没有提供这个功能, 那就开始动手写吧~app

首先在建立一个CustomTextView来继承UITextView:typecho

@interface CustomTextView : UITextView

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

@end

加入两个property:字体

@property (nonatomic, retain) NSString *placeholder; //文字
@property (nonatomic, retain) UIColor  *placeholderColor; //颜色

下一步就是具体实现了.m文件
先注册UITextViewTextDidChangeNotification来监听文字内容的改变, 初始化一些变量.atom

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:)
                                                     name:UITextViewTextDidChangeNotification
                                                   object:nil];
        
        self.autoresizesSubviews = NO;
        self.placeholder         = @"";
        self.placeholderColor    = [UIColor lightGrayColor];
        
    }
    return self;
}

而后就是最核心的部分, 重写- (void)drawRect:(CGRect)rect
先肯定好placeholder的位置(ios7中文字的位置和以前不同, 因此placeholder也要对应调一下位置),设置好颜色,用NSStringdrawInRect:绘制到TextView中.code

- (void)drawRect:(CGRect)rect
{
    //内容为空时才绘制placeholder
    if ([self.text isEqualToString:@""]) {
        CGRect placeholderRect;
        placeholderRect.origin.y = 8;
        placeholderRect.size.height = CGRectGetHeight(self.frame)-8;
        if (IOS_VERSION >= 7) {
            placeholderRect.origin.x = 5;
            placeholderRect.size.width = CGRectGetWidth(self.frame)-5;
        } else {
            placeholderRect.origin.x = 10;
            placeholderRect.size.width = CGRectGetWidth(self.frame)-10;
        }
        [self.placeholderColor set];
        [self.placeholder drawInRect:placeholderRect
                            withFont:self.font
                       lineBreakMode:NSLineBreakByWordWrapping
                           alignment:NSTextAlignmentLeft];
    }
}

- (void)drawRect:(CGRect)rectself绘制或大小位置改变的时候被调用,咱们输入文字是不会被调用的. 因此要调用selfsetNeedsDisplay来从新绘制self里面的内容(placeholder).server

- (void)textChanged:(NSNotification *)not
{
    [self setNeedsDisplay];
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    [self setNeedsDisplay];
}

一个简单的,带placeholderTextView就搞定了.若是须要给placeholder设置字体或别的属性, 能够按照上面的思路实现.继承

第一个文章其实很水, 慢慢来, 相信会愈来愈好. 虽然没什么含金量, 不过仍是把两个文件打包提供下载吧.ip

相关文章
相关标签/搜索