iOS UITextView的Placeholder占位文字

释放双眼,带上耳机,听听看~!
#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

调用

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

人已赞赏
iOS文章

ios python 国际化提取代码中的所有汉字

2020-3-6 13:44:55

iOS文章

iOS开发MBProgressHUD提示框(进度条)

2020-3-6 14:09:45

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索