UITextView 和 UITextField的区别
- UITextView支持多行输入并且可以滚动显示浏览全文,而UITextField只能单行输入。
- UITextView继承自UIScrollView,UITextField继承自UIView[UIControl]。
- UITextview没有placeholder属性 UItextField有placeholder属性在使用上我们完全可以把UITextView看作是UITextField的加强版。
首先我们要了解几个概念
在UIView中
1、自定义画图
- (void)drawRect:(CGRect)rect;
is invoked automaticall,never call it directly!!(自动调用,不会直接调用)
2、刷新视图
- (void)setNeedsDisplay;
When a view needs to be redrawn,use:(当视图需要重绘时调用此方法)
iOS的UITextView怎么实现placeholder
#import "SYTextView.h"
@implementation SYTextView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//先注册UITextViewTextDidChangeNotification来监听文字内容的改变, 初始化一些变量
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:)
name:UITextViewTextDidChangeNotification
object:nil];
self.autoresizesSubviews = NO;
self.placeholder = @"1234";
self.placeholderColor = [UIColor lightGrayColor];
self.backgroundColor = [UIColor blueColor];
}
return self;
}
//重写- (void)drawRect:(CGRect)rect先确定好placeholder的位置([ios7]中文字的位置和之前不一样, 所以placeholder也要对应调一下位置),设置好颜色,用NSString的drawInRect:绘制到TextView中.
- (void)drawRect:(CGRect)rect {
//内容为空时才绘制placeholder
if ([self.text isEqualToString:@""]) {
CGRect placeholderRect;
placeholderRect.origin.y = 8;
placeholderRect.size.height = CGRectGetHeight(self.frame)-8;
// if (IOS_VERSION >= 7) {
// placeholderRect.origin.x = 5;
// placeholderRect.size.width = CGRectGetWidth(self.frame)-5;
// } else {
placeholderRect.origin.x = 10;
placeholderRect.size.width = CGRectGetWidth(self.frame)-10;
// }
[self.placeholderColor set];
[self.placeholder drawInRect:placeholderRect
withFont:self.font
lineBreakMode:NSLineBreakByWordWrapping
alignment:NSTextAlignmentLeft];
}
}
//但- (void)drawRect:(CGRect)rect在self绘制或大小位置改变的时候被调用,我们输入文字是不会被调用的. 所以要调用self的setNeedsDisplay来重新绘制self里面的内容(placeholder).
- (void)textChanged:(NSNotification *)not
{
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text
{
[super setText:text];
[self setNeedsDisplay];
}
而且别忘记了
//注销通知 -(void) dealloc { [[NSNotificationCenter defaultCenter]removeObserver:self]; }