iOS Demo 详解(一) 占位符的TextView
2017-02-28 本文已影响12人
5a9c6f44e578
电脑中有很多demo,打算仔细研究下,顺便分享,挺多忘了原地址就不贴,非常抱歉
这次分享 JYHTextView
略有修改
效果

.h

.m
#import "JYHTextView.h"
@interface JYHTextView()
//占位 label
@property(nonatomic, weak)UILabel *placeholderLabel;
@end
@implementation JYHTextView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
//添加一个显示占位文字的Label
UILabel *placeholderLabel = [[UILabel alloc]initWithFrame:CGRectMake(3, 5, 200, 20)];
// 背景颜色透明
placeholderLabel.backgroundColor = [UIColor clearColor];
[self addSubview:placeholderLabel];
self.placeholderLabel = placeholderLabel;
//设置占位文字颜色
self.placeholderColor = [UIColor lightGrayColor];
//设置默认字体大小
self.font = [UIFont systemFontOfSize:15];
//设置监听通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
/**
* 移除本控制器所有的通知;
*/
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
* 文字内容改变时调用的方法
*/
- (void)textChange {
// 非0即为真 输入文字后 隐藏占位label
self.placeholderLabel.hidden = (self.text.length != 0);
}
/**
* set 赋值
*/
- (void)setPlaceholder:(NSString *)placeholder {
//copy 保证按钮 因为不可修改
_placeholder = [placeholder copy];
self.placeholderLabel.text = placeholder;
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
_placeholderColor = placeholderColor;
self.placeholderLabel.textColor = placeholderColor;
}
- (void)setText:(NSString *)text {
[super setText:text];
[self textChange];
}
@end
使用方法

demo 下载地址:
https://git.oschina.net/wwwzz/JYHTextView