項目要求, 話不多說, 下面直接開始.
第一種: 在自定義 textView 中添加一個 UILabel
這種可行是可行, 但是沒怎么見過人往 imageView 啊, textView 啊, 這種控件上面添加控件的, 感覺很怪~
思路就是添加 label 之后在輸入文本的時候隱藏 label, 沒有文本的時候顯示 label即可.
第二種: 利用消息傳遞, 關(guān)聯(lián)對象等底層實現(xiàn)占位符
這種比較麻煩, 弱雞如我并看得不順暢, 下面甩個鏈接.
點這里
第三種: 用 drawRect 方法直接畫一個 placeholder
這種方法我覺得可行度最高, 沒啥難度, 代碼最不麻煩.
首先我們新建一個自定義文件繼承自UITextView
, 然后我們考慮需要修改什么屬性, 首先這個自定義控件本身就繼承自系統(tǒng)控件, 那么font
, textColor
這些屬性可以直接外部修改就行了, 只需要自己設(shè)置占位文字和它的相關(guān)屬性即可(顏色, 字體等等), 如果想修改光標(biāo)顏色, 那么可能得用到runtime去用kvc修改系統(tǒng)屬性, 具體方法請參考這里, 可以試一下, 不知道可行不.
那么來到.h文件:
#import <UIKit/UIKit.h>
@interface ZYNPlaceholderTextView : UITextView
/** 占位符 */
@property (nonatomic, copy) NSString *zyn_placeholder;
/** 占位文字顏色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end
.h沒什么好說的
接下來, 來到.m文件:
這里得知道監(jiān)聽文字改變事件, 系統(tǒng)textView
自帶UITextViewTextDidChangeNotification
方法去監(jiān)聽.
首先重寫初始化方法:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self initPrivate];
}
return self;
}
- (void)initPrivate {
// 監(jiān)聽文字改變
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textDidChange)
name:UITextViewTextDidChangeNotification
object:nil];
}
/**
監(jiān)聽文字改變, 立馬顯示
*/
- (void)textDidChange {
[self setNeedsDisplay];
}
初始化方法就是監(jiān)聽一下文字改變了沒, 記得用完通知要在dealloc
里面釋放通知. 監(jiān)聽完文字改變, 我們就可以畫占位符了.
打開系統(tǒng)自己注釋掉的drawRect
方法:
- (void)drawRect:(CGRect)rect {
// Drawing code
// 如果有文字就不繪制占位文字
if ([self hasText]) {
return;
}
// 設(shè)置字體屬性
NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithCapacity:0];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor;
// 設(shè)置占位符大小區(qū)域
rect.origin.x = 5;
rect.origin.y = 7;
rect.size.width -= 2 * rect.origin.x;
rect.size.height -= 2 * rect.origin.y;
[self.zyn_placeholder drawInRect:rect
withAttributes:attrs];
}
至此, 大功告成, 可以使用了.
下面是使用方法:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ZYNPlaceholderTextView *textView = [[ZYNPlaceholderTextView alloc] initWithFrame:CGRectMake(10, 30, [UIScreen mainScreen].bounds.size.width - 20, [UIScreen mainScreen].bounds.size.height - 60)];
textView.backgroundColor = [UIColor grayColor];
textView.zyn_placeholder = @"這是一個占位符";
textView.font = [UIFont systemFontOfSize:22];
textView.textColor = [UIColor redColor];
textView.placeholderColor = [UIColor blueColor];
[self.view addSubview:textView];
}
最后上兩張效果圖:
輸入前
輸入后