起因
UITextView这个控件在开发中还是比较常用的,比如在用户的意见反馈和一些留言中.很遗憾系统方法里面没有为其设置PlaceHolder的方法和属性.以前也是临时解决PlaceHolder,没有很好的封装起来.今天抽了空为textView写了个分类.以后直接调用一个方法就可以实现添加PlaceHolder的需求了.
思路
为了做得更加通用,主要用到了runtime中的objc_setAssociatedObject和objc_getAssociatedObject动态为类添加新的属性.其次另外一个和当前输入的textView一样大小的充当PlaceHolder的角色.最后在代理中实现显示PlaceHolder的显示和隐藏.
图片示例
图片就不发了,没什么需要说明的
核心代码
.h文件
#import
@interfaceUITextView (XLPlaceHolder)
/**
*利用运行时动态添加的属性
*/
@property(nonatomic,strong)UITextView*placeHolderTextView;
/**
*设置placeHoloder.placeHoloder颜色默认为灰色
*
*@param placeHolder
*/
- (void)addPlaceHolder:(NSString*)placeHolder;
/**
*设置placeHoloder.placeHoloder颜色默认为自定义
*
*@param placeHolderplaceHolder
*@param placeHoloderTextColor自定义颜色
*/
- (void)addPlaceHolder:(NSString*)placeHolder placeHoloderTextColor:(UIColor*)placeHoloderTextColor;
@end
.m文件
#import"UITextView+XLPlaceHolder.h"
#import
staticconstchar*phTextView ="placeHolderTextView";
@implementationUITextView (XLPlaceHolder)
- (UITextView*)placeHolderTextView {
returnobjc_getAssociatedObject(self,phTextView);
}
- (void)setPlaceHolderTextView:(UITextView*)placeHolderTextView {
objc_setAssociatedObject(self,phTextView, placeHolderTextView,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)addPlaceHolder:(NSString*)placeHolder {
[selfaddPlaceHolder:placeHolderplaceHoloderTextColor:[UIColorgrayColor]];
}
- (void)addPlaceHolder:(NSString*)placeHolder placeHoloderTextColor:(UIColor*)placeHoloderTextColor{
if(![selfplaceHolderTextView]) {
self.delegate=self;
UITextView*textView = [[UITextViewalloc]initWithFrame:self.bounds];
textView.autoresizingMask=UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
textView.font=self.font;
textView.backgroundColor= [UIColorclearColor];
textView.textColor= placeHoloderTextColor;
textView.userInteractionEnabled=NO;
textView.text= placeHolder;
[selfaddSubview:textView];
[selfsetPlaceHolderTextView:textView];
}
}
# pragma mark -
# pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView*)textView {
self.placeHolderTextView.hidden=YES;
}
- (void)textViewDidEndEditing:(UITextView*)textView {
if(textView.text&& [textView.textisEqualToString:@""]) {
self.placeHolderTextView.hidden=NO;
}
}
@end
总结
一起自己对于运行时还是研究了一段时间,但是在实际工作中很少用到.常用的也就是那几种场景.动态为类添加属性,黑魔法(Swilling).希望简短的代码能够帮到需要的同学.
欢迎看看我的github地址:https://github.com/kingcodexl