用户反馈, 输入用户反馈信息的时候, 会有如下图所示的需求:
输入框可以多行输入, 并且包含占位文字, UITextField可以有占位符 但不支持多行输入, 所以不能使用UITextField. UITextView可以多行输入, 只需要添加上占位文字功能即可.
声明文件如下:.h文件
1 #import <UIKit/UIKit.h> 2 3 @interface PlaceholderTextView : UITextView 4 5 @property (nonatomic, strong) UILabel * placeHolderLabel; 6 7 @property (nonatomic, copy) NSString * placeholder; 8 9 @property (nonatomic, strong) UIColor * placeholderColor; 10 11 - (void)textChanged:(NSNotification * )notification; 12 13 @end
实现文件如下:.m文件
#import "PlaceholderTextView.h" @implementation PlaceholderTextView -(instancetype)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) { //设置一个占位文字初始的颜色 [self setPlaceholderColor:[UIColor lightGrayColor]]; //添加观察者 监听文字的变化 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil]; } return self; } //设置 -(void)setPlaceholder:(NSString *)placeholder{ if (_placeholder != placeholder) { _placeholder = placeholder; [self setNeedsDisplay]; } } - (void)textChanged:(NSNotification *)notification{ if ([[self placeholder] length] == 0) { return; } if ([[self text] length] == 0) { [[self viewWithTag:999] setAlpha:1.0]; } else{ [[self viewWithTag:999] setAlpha:0]; } } -(void)drawRect:(CGRect)rect{ [super drawRect:rect]; if ([[self placeholder] length] > 0) { if (_placeHolderLabel == nil) { _placeHolderLabel = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, self.bounds.size.width - 16, 0)]; _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping; _placeHolderLabel.numberOfLines = 0; _placeHolderLabel.font = self.font; _placeHolderLabel.backgroundColor = [UIColor clearColor]; _placeHolderLabel.textColor = self.placeholderColor; _placeHolderLabel.alpha = 0; _placeHolderLabel.tag = 999; [self addSubview:_placeHolderLabel]; } _placeHolderLabel.text = self.placeholder; [_placeHolderLabel sizeToFit]; [self sendSubviewToBack:_placeHolderLabel]; } if ([[self text] length] == 0 && [[self placeholder] length] >0) { [[self viewWithTag:999] setAlpha:1.0]; } } @end
注意:
999为常量, 应该写成常量表示, 或者用宏!
二: 输入框文字个数显示:
textView遵循协议, 设置代理,
#pragma mark textField的字数限制 //在这个地方计算输入的字数 - (void)textViewDidChange:(UITextView *)textView { NSInteger wordCount = textView.text.length; self.wordCountLabel.text = [NSString stringWithFormat:@"%ld/300",(long)wordCount]; if (textView.text.length < 300) { NSLog(@"%ld",textView.text.length); textView.editable = YES; } else{ textView.editable = NO; } }