項目開發中有時候需要給UITextView增加PlaceHolder,在以前的開發中封裝過這樣的一個類,繼承於UITextView,可直接設置PlaceHolder和顏色。
實現的思路是直接在UITextView中增加一個透明的不可響應事件的子UITextView,子UITextView的文字即爲PlachHolder。使用NSNotificationCenter監聽UITextView的輸入事件,根據是否存在文字來調整子UITextView的顯示和隱藏。
什麼都不說了,還是上代碼吧。。。因爲我平時是用純代碼寫界面的,所以該代碼只適合於純代碼寫界面的情況,其它情況請無視。。。
頭文件
//
// UIPlaceHolderTextView.h
// LoveLive
//
// Created by chaoye on 15/10/22.
// Copyright © 2015年 chaoye. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIPlaceHolderTextView : UITextView
@property (nonatomic, strong) NSString *placeHolder;
@property (nonatomic, strong) UIColor *placeHolderColor;
@end
實現文件
//
// UIPlaceHolderTextView.m
// LoveLive
//
// Created by chaoye on 15/10/22.
// Copyright © 2015年 chaoye. All rights reserved.
//
#import "UIPlaceHolderTextView.h"
@interface UIPlaceHolderTextView ()
@property (nonatomic, strong) UITextView *placeHolderTextView;
@end
@implementation UIPlaceHolderTextView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self addSubview:self.placeHolderTextView];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChanged:) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
- (UITextView *)placeHolderTextView {
if (!_placeHolderTextView) {
_placeHolderTextView = ({
UITextView *textView = [[UITextView alloc] initWithFrame:self.bounds];
textView.font = self.font;
textView.backgroundColor = [UIColor clearColor];
textView.textColor = [UIColor lightGrayColor];
textView.userInteractionEnabled = NO;
textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
textView;
});
}
return _placeHolderTextView;
}
- (void)textDidChanged:(NSNotification *)notification {
if (self.text.length > 0) {
[_placeHolderTextView setHidden:YES];
} else {
[_placeHolderTextView setHidden:NO];
}
}
- (void)setPlaceHolder:(NSString *)placeHolder {
_placeHolderTextView.text = placeHolder;
}
- (void)setPlaceHolderColor:(UIColor *)placeHolderColor {
_placeHolderTextView.textColor = placeHolderColor;
}
- (void)setText:(NSString *)text {
[super setText:text];
[self textDidChanged:nil];
}
- (void)setFont:(UIFont *)font {
[super setFont:font];
[_placeHolderTextView setFont:font];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end