新浪微博客户端(36)-自定义带placeholder的TextView

时间:2021-10-21 16:42:10

iOS 上自带的UITextView竟然不能设置placeholder,但是UITextView却可以,我也真是醉了。没办法了,自己写一个

DJTextView.h

#import <UIKit/UIKit.h>

@interface DJTextView : UITextView

@property (nonatomic,copy) NSString *placeholder;
@property (nonatomic,strong) UIColor *placeholderColor; @end

DJTextView.m

#import "DJTextView.h"

@implementation DJTextView

- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 在通知中心为TextView注册一个当文本改变的通知,当文本发生变化时,TextView会发一个通知
// 类似于android里面的BroadcastReceiver
// iOS 注册接收通知的方式为:addObserver name:
// android 注册接收通知的方式为:intent.addAction();
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textHasChange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
} // 当文字改变时会调用此方法
- (void)textHasChange { // setNeedsDisplay 类似于android里面的postInvalidate()方法,都是向操作系统发出请求重绘的消息
// 操作系统会在未来的时间内调用drawRect(iOS),onDraw(android);
// 注意:系统不允许我们自己调用drawRect或onDraw方法
[self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { if ([self hasText]) return; // 如果检测到当前TextView中有文本,就不再绘制 CGFloat placeholderRectX = ;
CGFloat placeholderRectY = ;
CGFloat placeholderRectW = rect.size.width - * placeholderRectX;
CGFloat placeholderRectH = rect.size.height - * placeholderRectY; // 将文本绘制在一个指定的矩形框内
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
// 若用户没有设置placeholder的颜色,则给placeholder设置一个默认颜色
attrs[NSForegroundColorAttributeName] = self.placeholderColor ? self.placeholderColor : [UIColor grayColor];
[self.placeholder drawInRect:CGRectMake(placeholderRectX, placeholderRectY, placeholderRectW, placeholderRectH) withAttributes:attrs]; } #pragma mark - 当用户手动更新当前字体属性时,就自动触发重绘
- (void)setText:(NSString *)text{ [super setText:text];
[self setNeedsDisplay]; } - (void)setFont:(UIFont *)font { [super setFont:font];
[self setNeedsDisplay]; } - (void)setPlaceholder:(NSString *)placeholder { _placeholder = placeholder;
[self setNeedsDisplay]; } - (void)setPlaceholderColor:(UIColor *)placeholderColor { _placeholderColor = placeholderColor;
[self setNeedsDisplay]; } - (void)dealloc { // 类似于android,通知中心在使用完毕后需要销毁
// iOS: [NSNotificationCenter defaultCenter] removeObserver:self]
// android: unRegister(mBroadcastReceiver);
[[NSNotificationCenter defaultCenter] removeObserver:self]; } @end

最终效果:

新浪微博客户端(36)-自定义带placeholder的TextView