1、解决问题
众所周知UITextField有一个 placeholder属性,起到占位文字或者是提示的作用,但是UITextView却没有这样一个属性,本文就是为了解决这个问题
2、封装一个RWTextView
RWTextView.h
#import <UIKit/UIKit.h>
@interface RWTextView : UIView
/**
* 创建一个带有占位文字的UITextView的对象View
*/
+ (instancetype)textView;
/**
* 占位文字
*/
@property (nonatomic, copy) NSString *placeholder;
/**
* 占位文字的字体大小
*/
@property (nonatomic, assign) CGFloat placeholderFout;
/**
* 占位文字的字体颜色
*/
@property (nonatomic, strong) UIColor *placeholderTitleColor;
@end
RWTextView.m
#import "RWTextView.h"
@interface RWTextView ()<UITextViewDelegate>
/**
* 占位文字
*/
@property (nonatomic, strong) UILabel *placeHolderLabel;
/**
* UITextView
*/
@property (nonatomic, strong) UITextView *textView;
@end
@implementation RWTextView
/**
* 创建一个带有占位文字的UITextView的对象View 类方法的实现
*/
+ (instancetype)textView {
return [[self alloc] init];
}
/**
* 初始化子控件
*/
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
/** 1、创建 占位文字 */
UILabel *placeHolderLabel = [[UILabel alloc] init];
self.placeHolderLabel = placeHolderLabel;
self.placeHolderLabel.textColor = [UIColor lightGrayColor];
[self addSubview:placeHolderLabel];
/** 2、创建 UItextView */
UITextView *textView = [[UITextView alloc] init];
textView.delegate = self;
textView.backgroundColor = [UIColor clearColor];
textView.backgroundColor = [UIColor brownColor];
textView.alpha = 0.3;
textView.tintColor = [UIColor yellowColor];
self.textView = textView;
[self addSubview:textView];
}
return self;
}
/** 子控件布局 */
- (void)layoutSubviews {
[super layoutSubviews];
self.placeHolderLabel.frame = CGRectMake(5, 0, self.bounds.size.width, 30);
self.textView.frame = self.bounds;
}
/** 设置占位文字 */
- (void)setPlaceholder:(NSString *)placeholder {
_placeholder = placeholder;
self.placeHolderLabel.text = self.placeholder;
}
/** 设置占位文字字体大小 */
- (void)setPlaceholderFout:(CGFloat)placeholderFout {
_placeholderFout = placeholderFout;
self.placeHolderLabel.font = [UIFont systemFontOfSize:placeholderFout];
}
/** 设置占位文字颜色 */
- (void)setPlaceholderTitleColor:(UIColor *)placeholderTitleColor {
_placeholderTitleColor = placeholderTitleColor;
self.placeHolderLabel.textColor = placeholderTitleColor;
}
#pragma mark - UITextViewDelegate代理
#pragma mark - 监听textView中内容的改变
- (void)textViewDidChange:(UITextView *)textView {
if (!textView.text.length) {
//显示提示文字
self.placeHolderLabel.hidden = NO;
} else {
//隐藏提示文字
self.placeHolderLabel.hidden = YES;
}
}
3、完整调用封装 对象
#import "ViewController.h"
#import "RWTextView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1、创建textView
RWTextView *textView = [RWTextView textView];
textView.placeholder = @"textView中的placeholder";
textView.frame = CGRectMake(100, 100, 200, 100);
textView.placeholderTitleColor = [UIColor lightGrayColor];
textView.placeholderFout = 14;
textView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:textView];
}
@end
网友评论