UITextView添加placeholder属性

1、问题说明
UITextview添加placeholder属性
2、问题解决
上代码
如果想直接下载的,可以点击如下链接,下载

@interface UITextView (placeholder)
/** 注意先设置textView的字体 */
@property (nonatomic,copy) NSString *placeholder;
@end
/** 注意先设置textView的字体 */

#import "UITextView+placeholder.h"
#import <objc/runtime.h>

#define LEFT_MARGIN 5
#define TOP_MARGIN  8

@implementation UITextView (placeholder)

- (NSString *)placeholder{
    return self.label.text;
}

- (void)setPlaceholder:(NSString *)placeholder{

    //赋值修改高度
    self.label.text = placeholder;
    [self changeLabelFrame];

    //监听文本改变,如果没有设置placeholder就不会监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:nil];
}

//文本修改
- (void)textDidChange:(NSNotification *)notify{
    self.label.hidden = self.text.length;
}

- (UILabel *)label{

    UILabel *label =  objc_getAssociatedObject(self, @"label");

    if (label == nil) {
        //没有就创建,并设置属性
        label = [[UILabel alloc] init];
        label.font = self.font;
        label.textColor = [UIColor grayColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.numberOfLines = 0;

        [self addSubview:label];

        //关联到自身
        objc_setAssociatedObject(self, @"label", label, OBJC_ASSOCIATION_RETAIN);

    }

    return label;
}

//计算frame
- (void)changeLabelFrame{
    //文字可显示区域
    CGSize size = CGSizeMake(self.bounds.size.width - 2*LEFT_MARGIN, CGFLOAT_MAX);
    //计算文字所占区域
    CGSize labelSize = [self.placeholder boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.label.font} context:nil].size;

    self.label.frame = CGRectMake(LEFT_MARGIN, TOP_MARGIN, labelSize.width, labelSize.height);
}
@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值