iOS之UITextView实现placeHolder占位文字的最佳方法

来源:互联网 发布:js插件的写法 编辑:程序博客网 时间:2024/06/05 14:07

在iOS开发中,UITextField和UITextView是最常用的文本输入类和文本展示类的控件。不同的是,UITextField中有一个placeholder属性,可以设置UITextField的占位文字,可是,Apple没有给UITextView公开提供一个类似于placeholder这样的属性来供开发者使用。但是,通过Runtime,我们发现,UITextView内部有个“_placeHolderLabel”的私有成员变量。这种方法有一定的风险,而且可移植性不强。
笔者参考了各种方法,推荐下面自定义的UITextView,不仅可移植性强、而且拓展性好,还可以随时修改自定义属性的值,我们只需要自定义一个UITextView,就可以一劳永逸了。

.h文件
@interface UITextViewPlaceholder : UITextView

/* 占位文字 /
@property (copy, nonatomic) NSString *placeholder;
/* 占位文字颜色 /
@property (strong, nonatomic) UIColor *placeholderColor;

@end

.m文件
@implementation UITextViewPlaceholder
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// 设置默认字体
self.font = [UIFont systemFontOfSize:14];
// 设置默认颜色
self.placeholderColor = [UIColor lightGrayColor];
// 使用通知监听文字改变
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (void)textDidChange:(NSNotification *)note {
// 会重新调用drawRect:方法
[self setNeedsDisplay];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 每次调用drawRect:方法,都会将以前画的东西清除掉
- (void)drawRect:(CGRect)rect {
// 如果有文字,就直接返回,不需要画占位文字
if (self.hasText) return;
// 属性
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor;
// 画文字
rect.origin.x = 5;
rect.origin.y = 8;
rect.size.width -= 2 * rect.origin.x;
[self.placeholder drawInRect:rect withAttributes:attrs];
}
- (void)layoutSubviews {
[super layoutSubviews];
[self setNeedsDisplay];
}

//#pragma mark - setter
- (void)setPlaceholder:(NSString *)placeholder {
_placeholder = [placeholder copy];
[self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
_placeholderColor = placeholderColor;
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font {
[super setFont:font];
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text {
[super setText:text];
[self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText {
[super setAttributedText:attributedText];
[self setNeedsDisplay];
}

@end

阅读全文
0 0
原创粉丝点击