一、使用KVC,查找textView内部变量
UITextView
1.新建UITextView的Category,命名为UITextView+PlaceHolder,.h和.m代码分别如下#import <UIKit/UIKit.h>
@interface UITextView (Placeholder)
@property (nonatomic, copy) NSString *placeHolder;
@end
#import "UITextView+Placeholder.h"
@implementation UITextView (Placeholder)
- (void)setPlaceHolder:(NSString *)placeHolder {
UILabel *placeHolderStr = [[UILabel alloc] init];
placeHolderStr.text = placeHolder;
placeHolderStr.numberOfLines = 0;
placeHolderStr.textColor = [UIColor lightGrayColor];
[placeHolderStr sizeToFit];
[self addSubview:placeHolderStr];
placeHolderStr.font = self.font;
[self setValue:placeHolderStr forKey:@"_placeholderLabel"];
}
@end
2.调用时引入头文件后
- (void)textViewplaceHolderMethod {
self.textView.layer.masksToBounds = YES;
self.textView.layer.cornerRadius = 4;
self.textView.layer.borderWidth = 0.5;
self.textView.layer.borderColor = [UIColor blackColor].CGColor;
self.textView.placeHolder = @"请留下您对我们的建议或意见";
}
1.具体思路:在UITextView的delegate方法中控制
self.textView.text = @"";
或者
self.placeHolderLabel.hidden = Yes;
2.具体代码(UITextView.text)
- (void)setupTextView {
self.textView.delegate = self;
self.textView.text = @"请输入您的建议";
self.textView.textColor = [UIColor lightGrayColor];
self.textView.layer.masksToBounds = YES;
self.textView.layer.cornerRadius = 4;
self.textView.layer.borderWidth = 0.5;
self.textView.layer.borderColor = [UIColor blackColor].CGColor;
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
if ([textView.text isEqualToString:@"请输入您的建议"]) {
self.textView.text = @"";
self.textView.textColor = [UIColor blackColor];
}
}
- (void)textViewDidEndEditing:(UITextView *)textView {
if (textView.text.length == 0) {
self.textView.text = @"请输入您的建议";
self.textView.textColor = [UIColor lightGrayColor];
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
注:这个方法的缺点是当你输入 “请输入您的建议” 后,键盘失去响应后,在点击想继续输入的时候,原输入的 “请输入您的建议” 会消失,所以比较推荐方法一。