UITextView的Placeholder占位文字

来源:互联网 发布:淘宝买什么产品好 编辑:程序博客网 时间:2024/06/02 02:06

自己写的一个小demo

#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];
1 0
原创粉丝点击