UITextView添加placeholder属性

给UITextView添加placeholder属性网上也有很多,我在这里提供最简洁的方法给已解决。主要方法是给UITextView添加分类,再利用KVC对UITextView的私有属性“_placeholderLabel”修改。直接上代码了。

#import <UIKit/UIKit.h>
//系统版本
#define HKVersion [[[UIDevice currentDevice] systemVersion] floatValue]

@interface UITextView (Placeholder)

-(void)setPlaceholder:(NSString *)placeholdStr placeholdColor:(UIColor *)placeholdColor;

@end


#import "UITextView+Placeholder.h"

@implementation UITextView (Placeholder)

-(void)setPlaceholder:(NSString *)placeholdStr placeholdColor:(UIColor *)placeholdColor
{
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = placeholdStr;
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = placeholdColor;
    placeHolderLabel.font = self.font;
    [placeHolderLabel sizeToFit];
    
    /*
     [self setValue:(nullable id) forKey:(nonnull NSString *)]
     ps: KVC键值编码,对UITextView的私有属性进行修改
     */
   if (HKVersion >= 8.3) {
        UILabel *placeholder = [self valueForKey:@"_placeholderLabel"];
        //防止重复
        if (placeholder) {
            return;
        }
        [self addSubview:placeHolderLabel];
        [self setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    }
}

@end


    //方法的实现部分(记得导入头文件"UITextView+Placeholder.h")
    UITextView *contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 300, 300, 60)];
    contentTextView.layer.cornerRadius = 6;
    contentTextView.layer.borderWidth = 0.6;
    contentTextView.layer.borderColor = [UIColor grayColor].CGColor;
    contentTextView.layer.masksToBounds = YES;
    contentTextView.font = [UIFont systemFontOfSize:13];
    //调用私有方法
    [contentTextView setPlaceholder:@"这是placeholder文字..." placeholdColor:[UIColor lightGrayColor]];
    [self.view addSubview:contentTextView];

效果图:
未编辑
编辑时
编辑后

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值