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

相關文章
相關標籤/搜索