UITextView添加placeholder属性
程序员文章站
2023-12-23 12:58:40
...
给UITextView添加placeholder属性网上也有很多,我在这里提供最简洁的方法给已解决。主要方法是给UITextView添加分类,再利用KVC对UITextView的私有属性“_placeholderLabel”修改。直接上代码了。
#import <UIKit/UIKit.h>
//系统版本
#define HKVersion [[[UIDevice currentDevice] systemVersion] floatValue]
@interface UITextView (Placeholder)
-(void)setPlaceholder:(NSString *)placeholdStr placeholdColor:(UIColor *)placeholdColor;
@end
#import "UITextView+Placeholder.h"
@implementation UITextView (Placeholder)
-(void)setPlaceholder:(NSString *)placeholdStr placeholdColor:(UIColor *)placeholdColor
{
UILabel *placeHolderLabel = [[UILabel alloc] init];
placeHolderLabel.text = placeholdStr;
placeHolderLabel.numberOfLines = 0;
placeHolderLabel.textColor = placeholdColor;
placeHolderLabel.font = self.font;
[placeHolderLabel sizeToFit];
/*
[self setValue:(nullable id) forKey:(nonnull NSString *)]
ps: KVC键值编码,对UITextView的私有属性进行修改
*/
if (HKVersion >= 8.3) {
UILabel *placeholder = [self valueForKey:@"_placeholderLabel"];
//防止重复
if (placeholder) {
return;
}
[self addSubview:placeHolderLabel];
[self setValue:placeHolderLabel forKey:@"_placeholderLabel"];
}
}
@end
//方法的实现部分(记得导入头文件"UITextView+Placeholder.h")
UITextView *contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 300, 300, 60)];
contentTextView.layer.cornerRadius = 6;
contentTextView.layer.borderWidth = 0.6;
contentTextView.layer.borderColor = [UIColor grayColor].CGColor;
contentTextView.layer.masksToBounds = YES;
contentTextView.font = [UIFont systemFontOfSize:13];
//调用私有方法
[contentTextView setPlaceholder:@"这是placeholder文字..." placeholdColor:[UIColor lightGrayColor]];
[self.view addSubview:contentTextView];
效果图: