前言
本文章主要針對UITextView的高度自增、以及增長高度上限設定,占位符設置等問題,利用Category添加相關屬性和成員變量來解決相關問題。
效果圖:
此處設置了最大自增高度到200
PlaceHolder解決方案
這里采用的是利用Runtime獲取到UITextView的一個私有屬性@"_placeholderLabel"
還有多種多樣的實現方式,大家可以參考作者VV木公子 史上最全的iOS之UITextView實現placeHolder占位文字的N種方法
此處有部分問題:
需要同時設置占位符的大小和UITextView的文字大小,盡量設置大小相同
textView.placeholder_font = [UIFont systemFontOfSize:14]; textView.font = [UIFont systemFontOfSize:14];
否則會造成光標與占位符位置有差異的現象如下圖:
當然,你也無需去設置placeholder_font,本分類會自動為您添加placeholder_font的大小與UITextView的大小相同。
為了讓placeholder大小與textView的起始位置對齊,在這里多處重新設置了placeholder_font和sizeFit屬性,否則會導致占位符位置有差異。當然,如果你的項目需求是占位符和textView的字體大小不同,此時就需要你微調此屬性
placeHolderLabel.frame=CGRectMake(5,self.textContainerInset.top, self.frame.size.width - 10,self.frame.size.height);
UITextView高度
1.屬性設置
此處只是暴露了一些屬性設置placeholder的相關文字大小.
@property (copy,nonatomic) NSString *placeholder;//占位符 @property (nonatomic,strong) UIColor *placeholder_color;//占位符字體顏色
2.為分類添加成員變量
@property (nonatomic,strong) UIFont *placeholder_font;//占位符大小 @property (nonatomic,assign) BOOL isAutoHeight;// 自動增長 @property (nonatomic,assign) CGFloat maxAutoHeight;// 最高增長高度 @property (nonatomic,assign) CGFloat minAutoHeight;// 最小收縮高度(默認初始化textView的高度,略顯雞肋)
因為類別只能"添加"屬性,并不能直接添加成員變量,但是Objective-C是運行時,動態語言,可以在其提供的runtime函數中找到一個class_addIvar()函數用于給類別添加成員變量.
在set方法中使用了
objc_setAssociatedObject(self,GYplaceholder_font,placeholder_font,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
get方法中:
objc_getAssociatedObject(self, GYplaceholder_font)
//利用靜態變量地址唯一不變的特性 static const void *GYplaceholder_font = &GYplaceholder_font;
蘋果官方文檔:
Sets an associated value for a given object using a given key and association policy.
func objc_setAssociatedObject(Any!, UnsafeRawPointer!, Any!, objc_AssociationPolicy)
Returns the value associated with a given object for a given key.
func objc_getAssociatedObject(Any!, UnsafeRawPointer!)
3.最后高度變化設置
//0.1 防止換行 時高度變化導致頂部文字位置移動 self.frame=CGRectMake(self.frame.origin.x,self.frame.origin.y, self.frame.size.width, height + 0.1);
minAutoHeight的設置:
如果不設置則默認minAutoHeight與textView的初始化高度相同,一般此minAutoHeight大小設置應大與初始化高度、如果設置小于首次初始化高度會產生部分差異.
最后,奉上源碼,請多多給出建議,謝謝,下載項目時,請記得切換Target到GYUIText-OC。