OC-通过Runtime为UITextView添加占位文字(支持Xib)

Swift版在这

代码设置

需要将#import "UITextView+HWCategory.h"导入PCH中

self.tv.placeholder = @"请输入";
self.tv.placeholderColor = [UIColor lightGrayColor];
xib设置
核心代码
  • .h文件
#import 

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 

@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

Dome

你可能感兴趣的:(OC-通过Runtime为UITextView添加占位文字(支持Xib))