UITextView的Placeholder占位文字

自己写的一个小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];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值