分类已经写好,直接拿来用即可
demo:
UITextView *textView = [[UITextView alloc] init];
textView.font = [UIFont systemFontOfSize:18.0]; //注意先设置字体,再设置placeholder
textView.placeholder = @"请输入您的问题...";
主要技术点:
用运行时动态绑定一个label来显示placeholder
详细代码:(已封装好的分类)
1 /** 注意先设置textView的字体 */ 2 3 #import "UITextView+placeholder.h" 4 #import <objc/runtime.h> 5 6 #define LEFT_MARGIN 5 7 #define TOP_MARGIN 8 8 9 @implementation UITextView (placeholder) 10 11 - (NSString *)placeholder{ 12 return self.label.text; 13 } 14 15 - (void)setPlaceholder:(NSString *)placeholder{ 16 17 //赋值修改高度 18 self.label.text = placeholder; 19 [self changeLabelFrame]; 20 21 //监听文本改变,如果没有设置placeholder就不会监听 22 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:nil]; 23 } 24 25 //文本修改 26 - (void)textDidChange:(NSNotification *)notify{ 27 self.label.hidden = self.text.length; 28 } 29 30 - (UILabel *)label{ 31 32 UILabel *label = objc_getAssociatedObject(self, @"label"); 33 34 if (label == nil) { 35 //没有就创建,并设置属性 36 label = [[UILabel alloc] init]; 37 label.font = self.font; 38 label.textColor = [UIColor grayColor]; 39 label.textAlignment = NSTextAlignmentLeft; 40 label.numberOfLines = 0; 41 42 [self addSubview:label]; 43 44 //关联到自身 45 objc_setAssociatedObject(self, @"label", label, OBJC_ASSOCIATION_RETAIN); 46 47 } 48 49 return label; 50 } 51 52 //计算frame 53 - (void)changeLabelFrame{ 54 //文字可显示区域 55 CGSize size = CGSizeMake(self.bounds.size.width - 2*LEFT_MARGIN, CGFLOAT_MAX); 56 //计算文字所占区域 57 CGSize labelSize = [self.placeholder boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.label.font} context:nil].size; 58 59 self.label.frame = CGRectMake(LEFT_MARGIN, TOP_MARGIN, labelSize.width, labelSize.height); 60 } 61 @end
打包地址:
https://github.com/iOSSinger/UITextView-placeholder.git
时间: 2024-10-19 15:38:57