首页 > 代码库 > 用户反馈

用户反馈

用户反馈, 输入用户反馈信息的时候, 会有如下图所示的需求:

技术分享

输入框可以多行输入, 并且包含占位文字, 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文件

 1 #import "PlaceholderTextView.h"
 2 
 3 @implementation PlaceholderTextView
 4 
 5 -(instancetype)initWithFrame:(CGRect)frame{
 6     
 7     if (self = [super initWithFrame:frame]) {
 8         
 9         [self setPlaceholder:@""];
10         
11         [self setPlaceholderColor:[UIColor lightGrayColor]];
12         
13         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
14         
15     }
16     
17     return self;
18 }
19 
20 -(void)setPlaceholder:(NSString *)placeholder{
21     
22     if (_placeholder != placeholder) {
23         
24         _placeholder = placeholder;
25         
26         [self.placeHolderLabel removeFromSuperview];
27         
28         self.placeHolderLabel = nil;
29         
30         [self setNeedsDisplay];
31         
32         
33     }
34     
35 }
36 
37 - (void)textChanged:(NSNotification *)notification{
38     
39     if ([[self placeholder] length] == 0) {
40         return;
41     }
42     
43     if ([[self text] length] == 0) {
44         [[self viewWithTag:999] setAlpha:1.0];
45     }
46     
47     else{
48         
49         [[self viewWithTag:999] setAlpha:0];
50     }
51     
52 }
53 
54 -(void)drawRect:(CGRect)rect{
55     
56     [super drawRect:rect];
57     
58     if ([[self placeholder] length] > 0) {
59         if (_placeHolderLabel == nil) {
60             _placeHolderLabel = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, self.bounds.size.width - 16, 0)];
61             _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
62             _placeHolderLabel.numberOfLines = 0;
63             _placeHolderLabel.font = self.font;
64             _placeHolderLabel.backgroundColor = [UIColor clearColor];
65             _placeHolderLabel.textColor = self.placeholderColor;
66             _placeHolderLabel.alpha = 0;
67             _placeHolderLabel.tag = 999;
68             [self addSubview:_placeHolderLabel];
69         }
70         _placeHolderLabel.text = self.placeholder;
71         [_placeHolderLabel sizeToFit];
72         [self sendSubviewToBack:_placeHolderLabel];
73     }
74     
75     if ([[self text] length] == 0 && [[self placeholder] length] >0) {
76         [[self viewWithTag:999] setAlpha:1.0];
77     }
78     
79 }
80 
81 
82 
83 @end

 

用户反馈