DeveKing7-给UITextView添加Placeholder最简单易懂的方法
来源:互联网 发布:c语言socket网络编程 编辑:程序博客网 时间:2024/05/13 03:10
今天项目里又需要写一个有占位符的UITextView控件,以前的话都是用代理来判断实现的,每个类里都需要判断,太麻烦了,所以为了便于以后再次用到需要占位符的UITextView,决定自己写一个自定义的UITextView,首先我想到的就是继承。网上也有很多利用分类Categories的方法,利用runtime和新增的UILabel控件来做这个占位符效果实在有点大智若愚。故自己写了一个,代码很简单,
.h文件
#import <UIKit/UIKit.h>
@interface WLTUITextView : UITextView
-(void)setPlaceholder:(NSString *)str and:(UIColor *)color;
@end
.m文件
#import "WLTUITextView.h"
@implementation WLTUITextView{
NSString * placheolder;
UIColor * _placeholderColor;
}
-(void)setPlaceholder:(NSString *)str and:(UIColor *)color{
_placeholderColor = color;
placheolder = str;
self.text = str;
self.textColor = _placeholderColor?_placeholderColor:[UIColorgrayColor];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(textDidBegin)name:UITextViewTextDidBeginEditingNotificationobject:self];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(textDidEnd)name:UITextViewTextDidEndEditingNotificationobject:self];
//这里使用KVO时,会出现死循环,因为占位符的逻辑问题。所以这里不适合用KVO故采用以上的方法更简单。网上的那些使用runtime机制又加了label来做占位符的方法实在是有点大智若愚的感觉。我觉得用最简单的代码解决复杂问题的能力就是一个人的逻辑思维能力。
}
-(void)textDidBegin{
if ([self.textisEqualToString:placheolder]) {
self.text =@"";
self.textColor = [UIColorblackColor];
}
}
-(void)textDidEnd{
if([self.textisEqualToString:@""]){
self.text =placheolder;
self.textColor =_placeholderColor?_placeholderColor:[UIColorgrayColor];
}
}
- DeveKing7-给UITextView添加Placeholder最简单易懂的方法
- 给UITextView添加PlaceHolder
- iOS给UITextView添加Placeholder
- 给UITextView添加类似placeholder功能
- UITextView 实现placeholder的方法
- UITextView 实现placeholder的方法
- UITextView 实现placeholder的方法
- UITextView设置placeholder的方法
- UITextView 实现placeholder的方法
- UITextView 实现placeholder的方法
- UITextView 实现placeholder的方法
- UITextView 实现placeholder的方法
- UITextView 添加placeholder
- UITextView添加Placeholder(swift)
- UITextView添加placeholder属性
- UITextView添加placeholder属性
- UITextView添加placeHolder
- UITextView添加placeholder属性
- Git fetch和git pull的区别
- python写入csv乱码问题
- SharePoint Framework 概述
- CSS的拓展选择器
- 【Java】IO整理之File类使用大全
- DeveKing7-给UITextView添加Placeholder最简单易懂的方法
- Github版本控制系统学习总结(一)---常用的Git命令
- 前端Scripts模块问题
- MonoDB的优势及劣势
- 重复读取InputStream的方法
- Maven核心_仓库
- iterator与iterable接口之间的区别
- 乐观锁 悲观锁实例
- extern "c"的使用问题