欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

借用runtime来实现UITextView的占位符placehold功能

程序员文章站 2022-05-29 23:50:59
...

1、 首先我们需要倒入runtime的头文件 #import <objc/runtime.h>

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);
#warning 通过打印可以发现 uitextField 有 ‘_placeholderLabel’占位符属性
    }

借用runtime来实现UITextView的占位符placehold功能
通过打印我没可以看到UITextField是存在placeholder属性的

  • 布局UITextField
- (void)setupTextView
{
    CGFloat margin = 15;
    UILabel *tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(margin, 0, SCREEN_width - 2 * margin, 50)];
    tipLabel.text = @"你的批评和建议能帮助我们更好的完善产品,请留下你的宝贵意见!";
    tipLabel.numberOfLines = 2;
    tipLabel.textColor = [UIColor colorWithRed:255 green:10 blue:10 alpha:1];
    tipLabel.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:tipLabel];

    CGFloat height  = 200;
#ifndef __IPHONE_4_0
    height = 100;
#endif
    UITextView *iderTextView = [[UITextView alloc] initWithFrame:CGRectMake(margin, CGRectGetMaxY(tipLabel.frame) + margin, SCREEN_width - 2 * margin, height)];
    iderTextView.backgroundColor = [UIColor whiteColor];
    iderTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    iderTextView.layer.borderWidth = 1;
    iderTextView.scrollEnabled = YES;
    iderTextView.scrollsToTop = YES;
    iderTextView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    //    iderTextView.delegate = self;
    self.iderTextView = iderTextView;
    [self.view addSubview:iderTextView];

    // _placeholderLabel
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"请输入宝贵意见(300字以内)";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.font = [UIFont systemFontOfSize:14];
    placeHolderLabel.textColor = [UIColor lightGrayColor];
    [placeHolderLabel sizeToFit];
    [iderTextView addSubview:placeHolderLabel];
#warning 通过‘_placeholderLabel’属性来设置他的占位符
    [iderTextView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    iderTextView.font =  placeHolderLabel.font;
}

借用runtime来实现UITextView的占位符placehold功能