VisionWallPaperOffline-8-19/HDwallpaper/Tool/CustomTextView.m
2024-07-23 15:14:59 +08:00

88 lines
2.4 KiB
Objective-C

//
// CustomTextView.m
// HD wallpaper
//
#import "CustomTextView.h"
@interface CustomTextView ()
@property (nonatomic, strong) UILabel *placeholderLabel;
@end
@implementation CustomTextView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self commonInit];
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self commonInit];
}
- (void)commonInit {
_placeholderColor = [UIColor lightGrayColor];
_borderColor = [UIColor grayColor];
_borderWidth = 1.0;
_cornerRadius = 5.0;
self.layer.borderColor = self.borderColor.CGColor;
self.layer.borderWidth = self.borderWidth;
self.layer.cornerRadius = self.cornerRadius;
self.placeholderLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.placeholderLabel.textColor = self.placeholderColor;
self.placeholderLabel.numberOfLines = 0;
[self addSubview:self.placeholderLabel];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:nil];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setPlaceholder:(NSString *)placeholder {
_placeholder = placeholder;
self.placeholderLabel.text = placeholder;
[self setNeedsLayout];
}
- (void)layoutSubviews {
[super layoutSubviews];
[self updatePlaceholderFrame];
self.placeholderLabel.hidden = self.hasText;
}
- (void)updatePlaceholderFrame {
CGFloat padding = self.textContainer.lineFragmentPadding;
CGFloat width = CGRectGetWidth(self.bounds) - padding * 2;
CGSize placeholderSize = [self.placeholderLabel sizeThatFits:CGSizeMake(width, CGFLOAT_MAX)];
self.placeholderLabel.frame = CGRectMake(padding, self.textContainerInset.top, width, placeholderSize.height);
}
- (void)textDidChange:(NSNotification *)notification {
self.placeholderLabel.hidden = self.hasText;
}
@end
//#import "CustomTextView.h"
//
//// 创建并添加CustomTextView
//CustomTextView *textView = [[CustomTextView alloc] initWithFrame:CGRectMake(20, 100, self.view.frame.size.width - 40, 150)];
//textView.placeholder = @"请输入内容...";
//textView.placeholderColor = [UIColor lightGrayColor];
//textView.borderColor = [UIColor blueColor];
//textView.borderWidth = 2.0;
//textView.cornerRadius = 10.0;
//[self.view addSubview:textView];