给UITextView添加placeholder属性

152 阅读1分钟

#.h文件

#import <UIKit/UIKit.h>

@interface UITextView (XLPlaceholder)<UITextViewDelegate>
- (void)xl_setPlaceholder:(NSString *)xl_placeholder;
@end

#.m文件

#import "UITextView+XLPlaceholder.h"
#import <objc/runtime.h>
static const char *xl_placeholderTextView = "xl_placeholderTextView";

@implementation UITextView (XLPlaceholder)

- (UITextView *)xl_placeholderTextView {
    return objc_getAssociatedObject(self, xl_placeholderTextView);
}
- (void)setxl_placeholderTextView:(UITextView *)placeholderTextView {
    objc_setAssociatedObject(self, xl_placeholderTextView, placeholderTextView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (void)xl_setPlaceholder:(NSString *)xl_placeholder{
    if (![self xl_placeholderTextView]) {
        UITextView *textView = [[UITextView alloc] initWithFrame:self.bounds];
        textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        textView.font = self.font;
        textView.backgroundColor = [UIColor clearColor];
        textView.textColor = [UIColor colorWithRed:0.78 green:0.78 blue:0.80 alpha:1.00];
        textView.userInteractionEnabled = NO;
        textView.text = xl_placeholder;
        [self addSubview:textView];
        [self setxl_placeholderTextView:textView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    self.xl_placeholderTextView.text = xl_placeholder;
}

#pragma mark ---  UITextViewDelegate监听textView的内容变化
-(void)textViewDidChange:(UITextView *)textView{
    if (self.text && [self.text isEqualToString:@""]) {
        self.xl_placeholderTextView.hidden = NO;
        return;
    }
    self.xl_placeholderTextView.hidden = YES;
}

#pragma mark ---  移除通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end