UITextField:
1.文字永远是一行,不能显示多行文字
2.有placehoder属性设置占位文字
3.继承自UIControl
4.监听行为
1> 设置代理
2> addTarget:action:forControlEvents:
3> 通知:UITextFieldTextDidChangeNotification
UITextView:
1.能显示任意行文字
2.不能设置占位文字
3.继承自UIScollView
4.监听行为
1> 设置代理
2> 通知:UITextViewTextDidChangeNotification
但是我们总会有特殊的要求:
(1)既可以多行输入又有占位文字
(2)当我们输入文字的时候占位文字消失
(3)当文字的个数为零的时候出现占位文字
我们可以重写UITextVie:(下面是几个主要方法)
- (void)drawRect:(CGRect)rect
{
// 如果有输入文字,就直接返回,不画占位文字(重画前,清楚之前画的内容)
if (self.hasText) return;
// 文字属性
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
// 画文字
// [self.placeholder drawAtPoint:CGPointMake(5, 8) withAttributes:attrs];
//上面的方法只能指定起始地点开始画
CGFloat x = 5;
CGFloat w = rect.size.width - 2 * x;
CGFloat y = 8;
CGFloat h = rect.size.height - 2 * y;
CGRect placeholderRect = CGRectMake(x, y, w, h);
//下面的方法在一定的范围能画,会自动换行
[self.placeholder drawInRect:placeholderRect withAttributes:attrs];
}
设置监听,当监听到输入的文字发生变化时,执行监听方法
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 通知
// 当UITextView的文字发生改变时,UITextView自己会发出一个UITextViewTextDidChangeNotification通知
[ [NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
/**
* 监听文字改变
*/
- (void)textDidChange
{
// 重绘(重新调用)
[self setNeedsDisplay];
}