目的:
我们在ios开发中textField的placeHolder属性是默认的占位符,当编辑的时候占位符自动去除,但是现在想在textView中实现这样一个属性。
实现:
笔者原来是在textView上添加了一个label,在textView编辑的代理方法里面实现label的透明度,后台封装了一个textView类方法,需要的时候直接调用就行了,下面请看代码
#import <UIKit/UIKit.h>
@protocol PlaceHolderTextViewDelegate <NSObject>
- (void)textViewDidChange:(NSString *)text;
@end
@interface PlaceHolderTextView : UITextView
/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字的颜色 */
@property (nonatomic, strong) UIColor *placeholderColor;
/** 输入文字 */
@property (nonatomic, copy) NSString *newtext;
@property (nonatomic, assign) id<PlaceHolderTextViewDelegate>YPDelegate;//代理方法
@end
#import "PlaceHolderTextView.h"
@interface PlaceHolderTextView () <UITextViewDelegate>
@end
@implementation PlaceHolderTextView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 通知
// 当UITextView的文字发生改变时,UITextView自己会发出一个UITextViewTextDidChangeNotification通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (id)init
{
if(self = [super init])
{
// 通知
// 当UITextView的文字发生改变时,UITextView自己会发出一个UITextViewTextDidChangeNotification通知
self.delegate = self;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
* 监听文字改变
*/
- (void)textDidChange
{
// 重绘(重新调用)
[self setNeedsDisplay];
}
- (void)textViewDidChange:(UITextView *)textView
{
NSString *newStr = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
self.newtext = newStr;
[self.YPDelegate textViewDidChange:newStr];
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = [placeholder copy];
[self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
_placeholderColor = placeholderColor;
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text
{
[super setText:text];
// setNeedsDisplay会在下一个消息循环时刻,调用drawRect:
[self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
[super setAttributedText:attributedText];
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
// 如果有输入文字,就直接返回,不画占位文字
if (self.hasText) return;
// 文字属性
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor: RGB(194, 194, 194);
// 画文字
CGFloat x = 5;
CGFloat w = rect.size.width - 2 * x;
CGFloat y = 8;
CGFloat h = rect.size.height - 2 * y;
CGRect placeholderRect = CGRectMake(x, y, w, h);
[self.placeholder drawInRect:placeholderRect withAttributes:attrs];
}