代码设置
需要将#import "UITextView+HWCategory.h"
导入PCH中
self.tv.placeholder = @"请输入";
self.tv.placeholderColor = [UIColor lightGrayColor];
xib设置
核心代码
- .h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UITextView (HWCategory)
/** <#注释#> */
@property(nonatomic, strong)IBInspectable NSString *placeholder;
/** <#注释#> */
@property(nonatomic, strong)IBInspectable UIColor *placeholderColor;
@end
NS_ASSUME_NONNULL_END
- .m文件
#import "UITextView+HWCategory.h"
#import <objc/message.h>
@interface UITextView()
/** <#注释#> */
@property(nonatomic, strong) UILabel *placeholderLabel;
@end
@implementation UITextView (HWCategory)
- (void)setPlaceholder:(NSString *)placeholder {
self.placeholderLabel.text = placeholder;
}
- (NSString *)placeholder {
return self.placeholderLabel.text;
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
self.placeholderLabel.textColor = placeholderColor;
}
- (UIColor *)placeholderColor {
return self.placeholderLabel.textColor;
}
- (void)setPlaceholderLabel:(UILabel *)placeholderLabel {
objc_setAssociatedObject(self, "hw_placeholderLabelKey", placeholderLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UILabel *)placeholderLabel {
UILabel * label = objc_getAssociatedObject(self, "hw_placeholderLabelKey");
if (!label) {
if (self.font == nil) { // 防止没大小时显示异常 系统默认设置14
self.font = [UIFont systemFontOfSize:14];
}
label = [[UILabel alloc] initWithFrame:self.bounds];
label.numberOfLines = 0;
label.font = self.font;
label.textColor = [UIColor lightGrayColor];
[label sizeToFit];
[self setValue:label forKey:@"_placeholderLabel"];
[self addSubview:label];
[self sendSubviewToBack:label];
objc_setAssociatedObject(self, "hw_placeholderLabelKey", label, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return label;
}
@end
网友评论