iOS 开发学习iOS开发的正确姿势Objective-C成长之路

UITextView- 设置placeholder占位文字

2016-07-01  本文已影响407人  Andy_WangPeng

----->在开发中,随着输入文字的增多,Textfile已经不能满足我们的需求了,它的不能换行功能,也是让我们着急一番。我们只有选择UITextView了,可是UITextView没有(placeholder)占位文字的功能,真是鱼和熊掌不可兼得。下面我们来实现一下:

WBPlaceholderTextView.m文件
#import "WBPlaceholderTextView.h"
@implementation WBPlaceholderTextView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//监听文本的输入
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (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];
}
- (void)textDidChange{
//重绘
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
//如果文本框有值就返回
if (self.hasText) return;
CGFloat X = 5;
CGFloat Y = 8;
CGFloat W = rect.size.width - 2 * X;
CGFloat H = rect.size.width - 2 * Y;
NSMutableDictionary *attrt = [NSMutableDictionary dictionary];
attrt[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
attrt[NSFontAttributeName] = self.font?self.font:[UIFont systemFontOfSize:17.0];
[self.placeholder drawInRect:CGRectMake(X, Y,W,H) withAttributes:attrt];
}
//移除通知,预防野指针
-(void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end

至此一个带有placeholder占位文字的Textview已经完成,喜欢请戳添加关注,我们一起讨论.

联系我QQ:2258026527

上一篇下一篇

猜你喜欢

热点阅读