iOS-实现UITextView占位文字的几种方法

方法一:通过UITextViewDelegate代理实现


#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, weak) UITextView *textView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
    self.textView = textView;
    textView.delegate = self;
    textView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:textView];
    
    if (textView.text.length < 1) {
        textView.text = @"说点什么呢...";
        textView.textColor=[UIColor grayColor];
    }
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.textView endEditing:YES];
}


#pragma mark - UITextViewDelegate

- (void)textViewDidBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@"说点什么呢..."]) {
        textView.text = @"";
        textView.textColor=[UIColor blackColor];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length < 1) {
        textView.text = @"说点什么呢...";
        textView.textColor = [UIColor grayColor];
    }
}

方法二:给UITextView添加一个UILabel子控件


#import "ViewController.h"
#import 

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextView *textView;

@end

@implementation ViewController

// 通过运行时,找到UITextView的一个“_placeHolderLabel”私有变量
- (void)getPlaceHolderLabel {
    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);
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // _placeholderLabel
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"请输入内容";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = [UIColor lightGrayColor];
    [placeHolderLabel sizeToFit];
    [self.textView addSubview:placeHolderLabel];
    [self.textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.textView endEditing:YES];
}


@end

方法二在测试时候发现问题:在Xib创建的UITextView没有问题,但是在纯代码创建的UITextView时候会出现占位文字向上偏移一部分的Bug,待解决...)

在就解决方法二Bug中看到一个比较全的方案:https://m.2cto.com/kf/201608/534005.html

你可能感兴趣的:(iOS-实现UITextView占位文字的几种方法)