uitextview的placeholder占位文字

自己写的一个小demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# import "ZHZTextView.h"
# define kMargin 7
# define kFontSize 17
@interface ZHZTextView ()<UITextViewDelegate>
@property (nonatomic, strong)UILabel *placeholderLabel;
@end
@implementation ZHZTextView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.delegate = self;
self.layer.cornerRadius = kMargin;
self.layer.borderWidth = 1;
self.font = [UIFont systemFontOfSize:kFontSize];
}
return self;
}
# pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
self.placeholderLabel.hidden = textView.text.length;
}
# pragma mark - getter and setter
- (UILabel *)placeholderLabel {
if (_placeholderLabel == nil) {
_placeholderLabel = [[UILabel alloc] init];
_placeholderLabel.textColor = [UIColor lightGrayColor];
_placeholderLabel.numberOfLines = 0;
}
return _placeholderLabel;
}
- (void)setPlaceholder:(NSString *)placeholder {
if (_placeholder != placeholder) {
//只有在 设置占位文本时 才加载 label
[self addSubview:self.placeholderLabel];
//设置占位文本
self.placeholderLabel.text = placeholder;
//文本 frame
NSDictionary *dict = @{
NSFontAttributeName: [UIFont systemFontOfSize:kFontSize]
};
CGRect rect = [placeholder boundingRectWithSize:CGSizeMake(self.frame.size.width - kMargin * 2, 0) options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:dict context:nil];
self.placeholderLabel.frame = CGRectMake(kMargin, kMargin, rect.size.width, rect.size.height);
}
}
@end

调用

1
2
3
ZHZTextView *textView = [[ZHZTextView alloc] initWithFrame:CGRectMake(50, 20, 275, 375)];
textView.placeholder = @"是来占位的我是来占位的我是来占位的我是来占位的我是来占位的";
[self.view addSubview:textView];

原文链接: http://blog.csdn.net/zhz459880251/article/details/50301263