UITextView添加占位符 placeholder

UITextField和UITextView是最常用的文本接受类和文本展示类的控件。UITextField和UITextView都可以输入文本,也都可以监听文本的改变。但不同的是,UITextField继承自UIControl这个抽象类。UITextView继承自UIScrollView这个实体类。这就导致了UITextView可以多行展示内容,并且还可以像UIScrollView一样滚动。而UITextField只能单独的展示一行内容。从这个角度,UITextView在功能上是优于UITextField的。
但是,UITextField中有一个placeholder属性,可以设置UITextField的占位文字,起到提示用户输入相关信息的作用。可是,UITextView就没那么幸运了,apple没有给UITextView提供一个类似于placeholder这样的属性来供开发者使用,但是需求中往往又需要用到UITextView这个控件且还需要占位符。所以,不多说,直接上代码:
 

 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];

        

        if ([objcName isEqualToString:@"_placeholderLabel"]) {

            

            UILabel *placeHolderLabel = [[UILabel alloc] init];

            placeHolderLabel.text = @"我是占位符";

            placeHolderLabel.numberOfLines = 0;

            placeHolderLabel.textColor = [UIColor lightGrayColor];

            [placeHolderLabel sizeToFit];

            [_surveyNoteTextView addSubview:placeHolderLabel];

            placeHolderLabel.font = _surveyNoteTextView.font;

            [_surveyNoteTextView setValue:placeHolderLabel forKey:@"_placeholderLabel"];

            

            break;

        }

    }

    

    free(ivars);

通过runtime,我发现,UITextView内部有一个名为“_placeHolderLabel”的私有成员变量。大家知道,Objective-C没有绝对的私有变量,因为我们可以通过KVC来访问私有变量。

原文地址:https://www.cnblogs.com/hauler/p/7503888.html