iOS之给TextView增加placeholder
2017-06-28 本文已影响33人
张大普奔
利用两个UITextView非常简单的实现给TextView增加placeholder的功能
.h
#import <UIKit/UIKit.h>
@interface ZCTextView : UIView
@property (nonatomic, strong) UITextView *placeholderTextView;
@property (nonatomic, strong) UITextView *textView;
@end
.m
#import "ZCTextView.h"
@interface ZCTextView()<UITextViewDelegate>
@end
@implementation ZCTextView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self addSubview:self.placeholderTextView];
[self addSubview:self.textView];
}
return self;
}
- (UITextView *)placeholderTextView
{
if (!_placeholderTextView) {
_placeholderTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 0, self.width-20, self.height)];
_placeholderTextView.font = [UIFont systemFontOfSize:15];
_placeholderTextView.textColor = UIColorFromRGB(0xcdcdcd);
_placeholderTextView.backgroundColor = [UIColor clearColor];
}
return _placeholderTextView;
}
- (UITextView *)textView
{
if (!_textView) {
_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 0, self.width-20, self.height)];
_textView.font = [UIFont systemFontOfSize:15];
_textView.textColor = UIColorFromRGB(0x595959);
_textView.backgroundColor = [UIColor clearColor];
_textView.delegate = self;
}
return _textView;
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
_placeholderTextView.hidden = YES;
}
- (void)textViewDidChangeSelection:(UITextView *)textView
{
if (STR_IS_NOT_EMPTY(self.textView.text)) {
_placeholderTextView.hidden = YES;
}else{
_placeholderTextView.hidden = NO;
}
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
if (STR_IS_NOT_EMPTY(self.textView.text)) {
_placeholderTextView.hidden = YES;
}else{
_placeholderTextView.hidden = NO;
}
}
@end
举例
@property (nonatomic, strong) ZCTextView *ContentTextView;
- (ZCTextView *)ContentTextView
{
if (!_ContentTextView) {
_ContentTextView = [[ZCTextView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150)];
_ContentTextView.placeholderTextView.text = @"这是默认提示文字";
_ContentTextView.backgroundColor = [UIColor whiteColor];
}
return _ContentTextView;
}