前言
iOS開發(fā)中谓罗,UITextField和UITextView是最常用的文本接受類和文本展示類的控件蜜猾。UITextField和UITextView都輸入文本,也都可以監(jiān)聽文本的改變讶请。不同的是颁湖,UITextField繼承自UIControl這個抽象類脚线。UITextView繼承自UIScrollView這個實(shí)體類搁胆。這就導(dǎo)致了UITextView可以多行展示內(nèi)容,并且還可以像UIScrollView一樣滾動邮绿。而UITextField只能單獨(dú)的展示一行內(nèi)容渠旁。從這個角度,UITextView在功能上是優(yōu)于UITextField的船逮。
但是顾腊,眾所周知,UITextField中有一個placeholder屬性傻唾,可以設(shè)置UITextField的占位文字投慈,起到提示用戶輸入相關(guān)信息的作用」诮荆可是伪煤,UITextView就沒那么幸運(yùn)了,apple沒有給UITextView提供一個類似于placeholder這樣的屬性來供開發(fā)者使用凛辣。而開發(fā)中抱既,我們經(jīng)常會遇到既要占位文字,又要可以多行展示并且可以滾動的控件,單純的UITextField或者UITextView都不能滿足這種產(chǎn)品上的需求扁誓。比如防泵,現(xiàn)在市面上的app大多都有一個用戶反饋的入口,如下圖(一)所示蝗敢。下面我就把自己能夠想到的方法匯總一下捷泞,讓更多的開發(fā)者知道,原來有這么多方法可以實(shí)現(xiàn)UITextView的占位文字寿谴。
方法一
1.把UITextView的text屬性當(dāng)成“placeholder”使用锁右。
2.在開始編輯的代理方法里清除“placeholder”。
3.在結(jié)束編輯的代理方法里根據(jù)條件設(shè)置“placeholder”。
特點(diǎn):這種方法的特點(diǎn)是咏瑟,當(dāng)用戶點(diǎn)擊了textView拂到,placeholder占位文字就會立馬消失,官方的placeholder是當(dāng)系統(tǒng)監(jiān)聽到用戶輸入了文字后placeholder才會消失码泞。
// 創(chuàng)建textView
UITextView *textView = [[UITextViewalloc]initWithFrame:CGRectMake(20,70,SCREEN.width-40,100)];
textView.backgroundColor= [UIColor whiteColor];
textView.text = @"我是placeholder";
textView.textColor = [UIColor grayColor];
textView.delegate = self;
[self.view addSubview:textView];
#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
if(textView.text.length < 1){
textView.text = @"我是placeholder";
textView.textColor = [UIColor grayColor];
}
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
if([textView.text isEqualToString:@"我是placeholder"]){
textView.text=@"";
textView.textColor=[UIColor blackColor];
}
}
方法二
1.創(chuàng)建textView
2.給textView添加一個UILabel子控件兄旬,作為placeholder
3.在文本改變的代理方法里面顯示/隱藏UILabel
特點(diǎn):該方法同樣也可以實(shí)現(xiàn)類似于placeholder的功能。相比較方法一余寥,方法二可以實(shí)現(xiàn)動態(tài)監(jiān)聽文本的改變领铐,并非彈出鍵盤就立即清除placeholder,只有當(dāng)用戶開始輸入文本的時候劈狐。placeholder才會消失罐孝。同樣,當(dāng)用戶清空文本的時候肥缔,placeholder又會重新顯示出來。
#import "WSViewController.h"
@interface WSViewController () <UITextViewDelegate>
@property(nonatomic, weak)UITextView *textView;
@property(nonatomic, weak)UILabel *placeHolder;
@end
@implementation WSViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setupTextView];
}
// 添加textView
- (void)setupTextView
{
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 74, SCREEN_WIDTH - 2 * 10, 200)];
textView.frame = CGRectMake(10, 74, SCREEN_WIDTH - 2 * 10, 200);
[self.view addSubview:textView];
self.textView = textView;
textView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);
textView.delegate = self;
[self setupPlaceHolder];
//在彈出的鍵盤上面加一個view來放置退出鍵盤的Done按鈕
UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
[topView setBarStyle:UIBarStyleDefault];
UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace, doneButton, nil];
[topView setItems:buttonsArray];
[textView setInputAccessoryView:topView];
}
// 給textView添加一個UILabel子控件
- (void)setupPlaceHolder
{
UILabel *placeHolder = [[UILabel alloc] initWithFrame:CGRectMake(15, -2, SCREEN_WIDTH - 2 * 15, 200)];
self.placeHolder = placeHolder;
placeHolder.text = @"我是placeholder";
placeHolder.textColor = [UIColor lightGrayColor];
placeHolder.numberOfLines = 0;
placeHolder.contentMode = UIViewContentModeTop;
[self.textView addSubview:placeHolder];
}
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
if (!textView.text.length) {
self.placeHolder.alpha = 1;
} else {
self.placeHolder.alpha = 0;
}
}
//關(guān)閉鍵盤
-(void) dismissKeyBoard{
[self.textView resignFirstResponder];
}
@end
同樣地思路汹来,我們也可以把作為占位文字的UILabel用UITextField或者UITextView來替換续膳,同樣可以實(shí)現(xiàn)帶placeholder的textView,在次就不在詳述收班。
方法三
1.自定義UITextView
2.給UITextView添加placeholder和placeholderColor屬性
3.重寫initWithFrame方法
4.添加通知監(jiān)聽文字改變
5.重寫drawRect:方法
6.重寫相關(guān)屬性的set方法
特點(diǎn):相比計(jì)較上面兩種方法坟岔,這種方法可移植性、拓展性更好摔桦,這種方法社付,不僅樂意隨意通過我們添加的placeholder屬性設(shè)置默認(rèn)文字,還可以通過我們添加的placeholderColor設(shè)置默認(rèn)文字的顏色邻耕。今后鸥咖,我們只需要寫好這么一個自定義UITextView,就可以一勞永逸兄世。
#import <UIKit/UIKit.h>
@interface WSPlaceholderTextView : UITextView
/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字顏色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end
#import "WSPlaceholderTextView.h"
@implementation WSPlaceholderTextView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
// 設(shè)置默認(rèn)字體
self.font = [UIFont systemFontOfSize:15];
// 設(shè)置默認(rèn)顏色
self.placeholderColor = [UIColor grayColor];
// 使用通知監(jiān)聽文字改變
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (void)textDidChange:(NSNotification *)note
{
// 會重新調(diào)用drawRect:方法
[self setNeedsDisplay];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
* 每次調(diào)用drawRect:方法啼辣,都會將以前畫的東西清除掉
*/
- (void)drawRect:(CGRect)rect
{
// 如果有文字,就直接返回御滩,不需要畫占位文字
if (self.hasText) return;
// 屬性
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor;
// 畫文字
rect.origin.x = 5;
rect.origin.y = 8;
rect.size.width -= 2 * rect.origin.x;
[self.placeholder drawInRect:rect withAttributes:attrs];
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self setNeedsDisplay];
}
#pragma mark - setter
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = [placeholder copy];
[self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
_placeholderColor = placeholderColor;
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text
{
[super setText:text];
[self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
[super setAttributedText:attributedText];
[self setNeedsDisplay];
}
@end
方法四
1.自定義UITextView
2.給UITextView添加placeholder和placeholderColor屬性
3.重寫initWithFrame方法
4.重寫drawRect:方法
5.重寫相關(guān)屬性的set方法
特點(diǎn):這個方法的和方法三很相似鸥拧,只是沒有利用通知來監(jiān)聽文本的改變,需要配合textViewDidChanged:這個文本改變的代理方法使用削解。
#import <UIKit/UIKit.h>
@interface WSTextView : UITextView
/** 占位文字 */
@property (nonatomic,copy) NSString *placeholder;
/** 占位文字顏色 */
@property (nonatomic,strong) UIColor *placeholderColor;
@end
#import "WSTextView.h"
@implementation WSTextView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.font = [UIFont systemFontOfSize:15];
self.placeholderColor = [UIColor lightGrayColor];
self.placeholder = @"請輸入內(nèi)容";
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor;
[self.placeholder drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) withAttributes:attrs];
}
// 布局子控件的時候需要重繪
- (void)layoutSubviews
{
[super layoutSubviews];
[self setNeedsDisplay];
}
// 設(shè)置屬性的時候需要重繪富弦,所以需要重寫相關(guān)屬性的set方法
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = placeholder;
[self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
_placeholderColor = placeholderColor;
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text
{
[super setText:text];
if (text.length) { // 因?yàn)槭窃谖谋靖淖兊拇矸椒ㄖ信袛嗍欠耧@示placeholder,而通 過代碼設(shè)置text的方式又不會調(diào)用文本改變的代理方法氛驮,所以再此根據(jù)text是否不為空判 斷是否顯示placeholder腕柜。
self.placeholder = @"";
}
[self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
[super setAttributedText:attributedText];
if (attributedText.length) {
self.placeholder = @"";
}
[self setNeedsDisplay];
}
@end
// 應(yīng)用的時候需要配合UITextView的文本改變的代理方法
#import "ViewController.h"
#import "WSTextView.h"
@interface ViewController ()<UITextViewDelegate>
// @property(nonatomic,weak) WSTextView *textView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
WSTextView *textView = [[WSTextView alloc] initWithFrame:CGRectMake(10, 20, self.view.frame.size.width, 30)];
textView.placeholder = @"ws";
textView.delegate = self;
[self.view addSubview:textView];
// textView.text = @"試試會不會調(diào)用文本改變的代理方法"; // 不會調(diào)用文本改變的代理方法
textView.attributedText = [[NSAttributedString alloc] initWithString:@"富文本"];
// self.textView = textView;
}
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(WSTextView *)textView // 此處取巧,把代理方法參數(shù)類型直接改成自定義的WSTextView類型,為了可以使用自定義的placeholder屬性媳握,省去了通過給控制器WSTextView類型屬性這樣一步碱屁。
{
if (textView.hasText) { // textView.text.length
textView.placeholder = @"";
} else {
textView.placeholder = @"ws";
}
}
@end
方法五
通過runtime,我們發(fā)現(xiàn)蛾找,UITextView內(nèi)部有一個名為“_placeHolderLabel”的私有成員變量娩脾。大家知道,Objective-C沒有絕對的私有變量打毛,因?yàn)槲覀兛梢酝ㄟ^KVC來訪問私有變量柿赊。
特點(diǎn):相對于上面的4種方法,這種方法更加取巧幻枉,雖然Apple官方?jīng)]有給我們開發(fā)者提供類似于placeholder的屬性碰声,但是通過運(yùn)行時,我們遍歷出了一個placeHolderLabel的私有變量熬甫。這種方法簡單易懂胰挑,代碼量少,推薦大家使用這種方法椿肩。
#import "ViewController.h"
#import <objc/runtime.h>
#import <objc/message.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 通過運(yùn)行時瞻颂,發(fā)現(xiàn)UITextView有一個叫做“_placeHolderLabel”的私有變量
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([UITextView class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
NSString *objcName = [NSString stringWithUTF8String:name];
NSLog(@"%d : %@",i,objcName);
}
[self setupTextView];
}
- (void)setupTextView
{
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 100];
[textView setBackgroundColor:[UIColor greenColor]];
[self.view addSubview:textView];
// _placeholderLabel
UILabel *placeHolderLabel = [[UILabel alloc] init];
placeHolderLabel.text = @"請輸入內(nèi)容";
placeHolderLabel.numberOfLines = 0;
placeHolderLabel.textColor = [UIColor lightGrayColor];
[placeHolderLabel sizeToFit];
[textView addSubview:placeHolderLabel];
[textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
}
@end