----->在开发中,随着输入文字的增多,
Textfile
已经不能满足我们的需求了,它的不能换行功能,也是让我们着急一番。我们只有选择UITextView
了,可是UITextView
没有(placeholder)
占位文字的功能,真是鱼和熊掌不可兼得。下面我们来实现一下:
-
我们自定义一个UITextView
WBPlaceholderTextView.h文件
#import <UIKit/UIKit.h>
@interface WBPlaceholderTextView : UITextView
/占位文字/
@property(nonatomic,copy) NSString placeholder;
/展位文字的颜色*/
@property(nonatomic,strong) UIColor *placeholderColor;
@end
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已经完成,喜欢请戳添加关注
,我们一起讨论.
网友评论