用runtime给textView添加placeholder

来源:互联网 发布:win10更改Mac 编辑:程序博客网 时间:2024/05/21 21:38

#import <objc/runtime.h>

#import <objc/message.h>

@interface ViewController ()

@property (nonatomic,strong) UITextView *textView;


@end

@implementation ViewController

- (void)viewDidLoad {

// 通过运行时,发现UITextView有一个叫做“_placeHolderLabel”的私有变量

    unsignedint count = 0;

    Ivar *ivars =class_copyIvarList([UITextViewclass], &count);

    

    for (int i =0; i < count; i++) {

        Ivar ivar = ivars[i];

        constchar *name = ivar_getName(ivar);

        NSString *objcName = [NSStringstringWithUTF8String:name];

        NSLog(@"%d : %@", i, objcName);

    }

    

    [selfsetupTextView];

}


- (void)setupTextView {

    UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(010, 200, 100)];

    _textView = textView;

    [_textViewsetBackgroundColor:[UIColorwhiteColor]];

    // _placeholderLabel

    UILabel *placeHolderLabel = [[UILabelalloc] init];

    placeHolderLabel.text =@"请填写地址";

    placeHolderLabel.numberOfLines =0;

    placeHolderLabel.textColor = [UIColorcolorWithRed:208 /255.0 green:208 /255.0 blue:208 /255.0 alpha:1.0];

    [placeHolderLabel sizeToFit];

    [_textViewaddSubview:placeHolderLabel];

    [_textViewsetValue:placeHolderLabelforKey:@"_placeholderLabel"];

}



0 0