自定义含Placeholder的UITextView
2016-07-14 本文已影响239人
断剑
在我们的项目中经常会用到UITextView文本输入框,但是系统的textView没有想textFieldView一样有placeholder属性来方便我们的使用。今天把项目中自己写的一个自定义控件分享给大家
效果图- 先上代码
//
// ZZYPlaceholderTextView.m
// VTEAM
//
// Created by admin on 16/7/12.
// Copyright © 2016年 断剑. All rights reserved.
//
#import "ZZYPlaceholderTextView.h"
@interface ZZYPlaceholderTextView()
@property (nonatomic, weak) UILabel * placeholderLabel;
@end
@implementation ZZYPlaceholderTextView
- (void)awakeFromNib
{
[self setUp];
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self setUp];
}
return self;
}
- (void)setUp
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange:) name:UITextViewTextDidChangeNotification object:self];
CGFloat left = (self.leftMargin)?self.leftMargin:5;
CGFloat top = (self.topMargin)?self.topMargin:5;
CGFloat width = CGRectGetWidth(self.frame) - 2 * self.leftMargin;
CGFloat height = (self.placeHeight)?self.placeHeight:21;
UILabel * placeholderLabel = [[UILabel alloc]initWithFrame:CGRectMake(left, top, width,height)];
placeholderLabel.textColor = (self.placeholderColor)?self.placeholderColor:[UIColor lightGrayColor];
placeholderLabel.font = (self.placeholderFont)?self.placeholderFont:self.font;
placeholderLabel.text = self.placeholder;
[self addSubview:placeholderLabel];
self.placeholderLabel = placeholderLabel;
}
- (void)textChange:(NSNotification *)nofi
{
if (self.placeholder.length == 0 || [self.placeholder isEqualToString:@""]) {
self.placeholderLabel.hidden = YES;
}
if (self.text.length > 0) {
self.placeholderLabel.hidden = YES;
}
else
{
self.placeholderLabel.hidden = NO;
}
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = placeholder;
if (placeholder.length == 0 || [self.placeholder isEqualToString:@""]) {
self.placeholderLabel.hidden = YES;
}
else
{
self.placeholderLabel.text = placeholder;
self.placeholderLabel.hidden = NO;
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
-
思路分析
- 在UITExtView内部创建一个label,在外部为label设置各种属性
-
通过UITextView系统检测内部文字改变的通知,动态控制label的显示和隐藏状态
-
使用方法
-
xib使用
- 设置UITextView的类
- 拖线设置属性
-
代码用法
ZZYPlaceholderTextView * placeView = [[ZZYPlaceholderTextView alloc]initWithFrame:CGRectMake(20, 350, self.view.frame.size.width - 40 , 100)];
placeView.placeholder = @"请输入描述文字";
[self.view addSubview:placeView];