UITextField 天生就有 placeholder 屬性,UITextView 卻沒有。若多行輸入框也需要灰色提示文字,就得自己模擬一個。
思路很直接:繼承 UITextView,在文字為空時讓 super 的 text 顯示佔位字串,並搭配通知機制監聽開始與結束編輯的時機。
#import <UIKit/UIKit.h> @interface UIPlaceholderTextView : UITextView @property (nonatomic, strong) NSString *placeholder; // 佔位文字 - (void)addObserver; // 註冊通知 - (void)removeobserver; // 移除通知 @end
#import "UIPlaceholderTextView.h"
@interface UIPlaceholderTextView ()
@property (nonatomic, strong) UIColor *textColor;
- (void)beginEditing:(NSNotification *)notification;
- (void)endEditing:(NSNotification *)notification;
@end
@implementation UIPlaceholderTextView
@synthesize placeholder;
@synthesize textColor;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self awakeFromNib];
}
return self;
}
// 以 nib/storyboard 建立時會呼叫此方法
- (void)awakeFromNib {
textColor = [UIColor redColor];
[self addObserver];
}
#pragma mark - 通知
- (void)addObserver {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(beginEditing:)
name:UITextViewTextDidBeginEditingNotification
object:self];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(endEditing:)
name:UITextViewTextDidEndEditingNotification
object:self];
}
- (void)removeobserver {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Setter / Getter
- (void)setPlaceholder:(NSString *)aPlaceholder {
placeholder = aPlaceholder;
[self endEditing:nil];
}
// 外部讀到的 text 若是佔位文字,一律視為空字串
- (NSString *)text {
NSString *text = [super text];
if ([text isEqualToString:placeholder]) return @"";
return text;
}
- (void)beginEditing:(NSNotification *)notification {
if ([super.text isEqualToString:placeholder]) {
super.text = nil;
[super setTextColor:textColor];
}
}
- (void)endEditing:(NSNotification *)notification {
if ([super.text isEqualToString:@""] || super.text == nil) {
super.text = placeholder;
[super setTextColor:[UIColor lightGrayColor]];
}
}
@end
可以從 xib 拉一個 UITextView 並改其 class 為 UIPlaceholderTextView,也可以用 initWithFrame: 直接建立。無論哪一種,都別忘了設定 placeholder,並在適當時機註冊與移除通知。
- (void)viewDidLoad {
[super viewDidLoad];
self.textView.placeholder = @"請填寫你的資訊……";
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.textView addObserver];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self.textView removeobserver];
}
通知的註冊與移除成對出現很重要,否則在 viewDidDisappear 之後若物件被回收,通知仍可能打向已失效的記憶體位置。把 addObserver 放在 viewDidAppear、removeobserver 放在 viewDidDisappear,是較安全的配對方式。
此外,從 iOS 6 起 UITextView 本身已不建議用 this 方式自刻 placeholder;若專案 deployment target 允許,直接使用系統 API 會更省事。上述做法的價值在於理解通知機制與副類別覆寫 text 這兩個技巧。