我們都知道iOS開發中的UITextField有個placeholder屬性,placeholder可以很方便引導用戶輸入。但是UITextView卻沒有placeholder屬性。
一、猥瑣的方法
如何讓UITextView也有placeholder功能呢?今天給各位分享一個比較猥瑣的做法。思路大概是這樣的:
實現方法:
1.創建UITextView:
別忘了設置UITextView的代理,因為后面我們要用到UITextView的兩個代理方法。
2.開始編輯的代理方法:
if ([textView.text isEqualToString:@"VeVB.COm"]) {
textView.text = @"";
textView.textColor = [UIColor blackColor];
}
}
3.結束編輯的代理方法:
4.添加輕擊手勢
//輕擊手勢觸發方法
-(void)tapGesture:(UITapGestureRecognizer *)sender
{
[self.view endEditing:YES];
}
Demo地址:iOSStrongDemo
二、通常的方法
接下來來看比較通常的方法,哈哈~那么,這一次我將簡單的封裝一個UITextView。暫且取名叫GGPlaceholderTextView,GG前綴看著有點任性的哈。
GGPlaceholderTextView簡介:
GGPlaceholderTextView也是對text操作,具體邏輯如下:
繼承UITextView,并設置placeholder屬性:
注冊開始編輯和結束編輯通知,然后對text做相應的操作
通過UIApplicationWillTerminateNotification通知,在APP退出的時候移除通知。
我把GGPlaceholderTextView寫在下面。不過,微信里看代碼還是不太方便,我已經把代碼push到:iOSStrongDemo。你可以下載下來。
#import <UIKit/UIKit.h>
@interface GGPlaceholderTextView : UITextView
@property(nonatomic, strong) NSString *placeholder;
@end
#import "GGPlaceholderTextView.h"
@implementation GGPlaceholderTextView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self addObserver];
}
return self;
}
- (id)init {
if (self = [super init]) {
[self addObserver];
}
return self;
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = placeholder;
self.text = placeholder;
self.textColor = [UIColor grayColor];
}
-(void)addObserver
{
//注冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndEditing:) name:UITextViewTextDidEndEditingNotification object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(terminate:) name:UIApplicationWillTerminateNotification object:[UIApplication sharedApplication]];
}
- (void)terminate:(NSNotification *)notification {
//移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didBeginEditing:(NSNotification *)notification {
if ([self.text isEqualToString:self.placeholder]) {
self.text = @"";
self.textColor = [UIColor blackColor];
}
}
- (void)didEndEditing:(NSNotification *)notification {
if (self.text.length<1) {
self.text = self.placeholder;
self.textColor = [UIColor grayColor];
}
}
@end
實踐:
GGPlaceholderTextView *textView = [[GGPlaceholderTextView alloc] initWithFrame:CGRectMake(0, 64, SCREEN.width , 200)];
textView.backgroundColor = [UIColor whiteColor];
textView.placeholder = @"VeVB.COm";
[self.view addSubview:textView];
新聞熱點
疑難解答