美文网首页
TextView placeHolder

TextView placeHolder

作者: y2015 | 来源:发表于2018-01-19 10:42 被阅读9次

    TextView有placeHolderLabel这个私有属性,我们可以用万能的kvc调用

    #import "ViewController.h"
    #import <objc/runtime.h>
    #import <objc/message.h>
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
      // 通过运行时,发现UITextView有一个叫做“_placeHolderLabel”的私有变量
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([UITextView class], &count);
    
        for (int i = 0; i < count; i++) {
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            NSString *objcName = [NSString stringWithUTF8String:name];
            NSLog(@"%d : %@",i,objcName);
        }
    
    }
    @end
    

    所以我们只需以下方式就可以给textView添加placeholder

    - (void)setupTextView
    {
        UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 100];
        [textView setBackgroundColor:[UIColor greenColor]];
        [self.view addSubview:textView];
    
        // _placeholderLabel
        UILabel *placeHolderLabel = [[UILabel alloc] init];
        placeHolderLabel.text = @"请输入内容";
        placeHolderLabel.numberOfLines = 0;
        placeHolderLabel.textColor = [UIColor lightGrayColor];
        [placeHolderLabel sizeToFit];
        [textView addSubview:placeHolderLabel];//这句很重要不要忘了
    
        // same font
        textView.font = [UIFont systemFontOfSize:13.f];
        placeHolderLabel.font = [UIFont systemFontOfSize:13.f];
    
        [textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    }
    

    相关文章

      网友评论

          本文标题:TextView placeHolder

          本文链接:https://www.haomeiwen.com/subject/fopgwxtx.html