给UITextView添加placeholder属性

#.h文件

#import <UIKit/UIKit.h>

@interface UITextView (XLPlaceholder)<UITextViewDelegate>
- (void)xl_setPlaceholder:(NSString *)xl_placeholder;
@end
复制代码

#.m文件

#import "UITextView+XLPlaceholder.h"
#import <objc/runtime.h>
static const char *xl_placeholderTextView = "xl_placeholderTextView";

@implementation UITextView (XLPlaceholder)

- (UITextView *)xl_placeholderTextView {
    return objc_getAssociatedObject(self, xl_placeholderTextView);
}
- (void)setxl_placeholderTextView:(UITextView *)placeholderTextView {
    objc_setAssociatedObject(self, xl_placeholderTextView, placeholderTextView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (void)xl_setPlaceholder:(NSString *)xl_placeholder{
    if (![self xl_placeholderTextView]) {
        UITextView *textView = [[UITextView alloc] initWithFrame:self.bounds];
        textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        textView.font = self.font;
        textView.backgroundColor = [UIColor clearColor];
        textView.textColor = [UIColor colorWithRed:0.78 green:0.78 blue:0.80 alpha:1.00];
        textView.userInteractionEnabled = NO;
        textView.text = xl_placeholder;
        [self addSubview:textView];
        [self setxl_placeholderTextView:textView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    self.xl_placeholderTextView.text = xl_placeholder;
}

#pragma mark ---  UITextViewDelegate监听textView的内容变化
-(void)textViewDidChange:(UITextView *)textView{
    if (self.text && [self.text isEqualToString:@""]) {
        self.xl_placeholderTextView.hidden = NO;
        return;
    }
    self.xl_placeholderTextView.hidden = YES;
}

#pragma mark ---  移除通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
复制代码

转载于:https://juejin.im/post/5a321064f265da430a5098af

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值