项目开发中有时候需要给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