在我们的开始过程中,会遇到写评价的需求,这时我们就需要用到TextView,但是TextView跟TextField不同,TextField有自带的placeholder提示字属性,而TextView没有,在这里我写了一个简单带有placeholder提示字的TextView控件,仅供大家参考。
textView显示提示字.gif代码如下:
HCTextView.h 文件
/**
* 提示字label
*/
@property (nonatomic, strong) UILabel * placeHolderLabel;
/**
* 提示字
*/
@property (nonatomic, strong) NSString * placeholder;
/**
* 提示字颜色
*/
@property (nonatomic, strong) UIColor * placeholderColor;
/**
* 提示字字体大小
*/
@property (nonatomic, strong) UIFont * placeholderFont;
HCTextView.m 文件
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
if ([[self placeholder] length] > 0) {
if (_placeHolderLabel == nil) {
_placeHolderLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 8, self.bounds.size.width - 16, 0)];
_placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
_placeHolderLabel.numberOfLines = 0;
_placeHolderLabel.font = self.placeholderFont;
_placeHolderLabel.backgroundColor = [UIColor clearColor];
_placeHolderLabel.textColor = self.placeholderColor;
_placeHolderLabel.tag = 888;
[self addSubview:_placeHolderLabel];
}
_placeHolderLabel.text = self.placeholder;
[_placeHolderLabel sizeToFit];
[self sendSubviewToBack:_placeHolderLabel];
}
if ([[self text] length] == 0 && [[self placeholder] length] >0) {
[self viewWithTag:888].hidden = NO; //设置提示字显示
}
}
为了改变提示字的显示状态我们注册一个通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil]; //注册textView输入内容改变的通知
实现通知的方法
- (void)textChanged:(NSNotification *)notification{
if ([[self placeholder] length] == 0) {
return;
}
if ([[self text] length] == 0) { //输入内容为空
[self viewWithTag:888].hidden = NO; // 提示字显示
}
else {//输入内容不为空
[self viewWithTag:888].hidden = YES; //提示字隐藏
}
}
附加:
写评价的时候往往有字数限制,这是我的解决方法
//限制输入字数
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if (textView == self.textView) {
if (text.length == 0) return YES;
NSInteger existedLength = textView.text.length;
NSInteger selectedLength = range.length;
NSInteger replaceLength = text.length;
if (existedLength - selectedLength + replaceLength > 80) {
return NO;//字数大于80则不能输入,但是可以删除后在输入,网上有很多都不能再操作了
}
}
return YES;
}
这是我写的 Demo 仅供参考
网友评论