最近在做一个关于微博的项目,用到了UITextView发现系统自带的没有placeholder这个属性设置,于是自己写了一个自定义UITextView,觉得挺好用的,希望能和爱好iOS开发的伙伴们一起分享。
实验原理:通过
NSString的绘制实现 :如下
- (void)drawInRect:(CGRect)rect withAttributes:(nullable NSDictionary<NSString *, id> *)attrs NS_AVAILABLE(10_0, 7_0);
直接上代码:可以直接带走(应该没有任何耦合性)
PYTextView.h 代码如下
#import <UIKit/UIKit.h>
@interface PYTextView : UITextView
/** 占位符 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位符颜色*/
@property (nonatomic, strong) UIColor *placeholderColor;
@end
PYTextView.m 代码如下
#import "PYTextView.h"
@implementation PYTextView
@dynamic delegate;
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 通过通知监听文本变化
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (void)textDidChange
{
// 重绘
[self setNeedsDisplay];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = placeholder;
// 重绘
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
// 重绘
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text
{
[super setText:text];
// 发出通知
[[NSNotificationCenter defaultCenter] postNotificationName:UITextViewTextDidChangeNotification object:self];
// 重绘
[self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
[super setAttributedText:attributedText];
// 发出通知
[[NSNotificationCenter defaultCenter] postNotificationName:UITextViewTextDidChangeNotification object:self];
// 重绘
[self setNeedsDisplay];
}
- (void)setContentOffset:(CGPoint)contentOffset
{
[super setContentOffset:contentOffset];
// 重绘
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
if (self.text.length) return;
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
// 设置字体大小
attr[NSFontAttributeName] = self.font;
// 默认字体颜色为灰色
attr[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
// 设置绘画的位置,范围
CGFloat drawX = 5;
CGFloat drawY = 8;
CGFloat drawW = rect.size.width - 2 * drawX;
CGFloat drawH = rect.size.height - 2 * drawY;
CGRect placeholderRect = CGRectMake(drawX, drawY, drawW, drawH);
[self.placeholder drawInRect:placeholderRect withAttributes:attr];
}
@end
// 使用方法十分简单,直接设置placeholder属性的值就可以了,颜色、字体大小都可以自定义的哦。希望能帮到看过的朋友!