iOS给UITextView添加placeholder

实现方法:通过监听UITextView的文本变化,重绘UITextView将placeholder绘制出来。

支持xib实时预览placeholder效果。


UITextViewWithPlaceHolder.h文件

#import <UIKit/UIKit.h>

//在定义类的前面加上IB_DESIGNABLE宏,实现控件在xib或storyboard上可以实时渲染

IB_DESIGNABLE

@interface UITextViewWithPlaceHolder :UITextView

//在属性前面加上IB_DESIGNABLE宏,使该属性在xib或storyboard上可以展示

@property(nonatomic,strong) IBInspectable NSString*placeHolder;

@property(nonatomic,strong)UIFont *placeHolderFont;

@property(nonatomic,strong)UIColor *placeHolderColor;

@end


UITextViewWithPlaceHolder.m文件

#import"UITextViewWithPlaceHolder.h"

@implementation UITextViewWithPlaceHolder

- (instancetype)initWithCoder:(NSCoder*)coder

{

self= [super initWithCoder:coder];

if(self) {

[self addNofity];

}

returnself;

}

- (instancetype)initWithFrame:(CGRect)frame

{

self= [super initWithFrame:frame];

if(self) {

[self addNofity];

}

returnself;

}

- (void)addNofity{

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange:)name:UITextViewTextDidChangeNotification object:self];

}

- (void)removeNotify{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect {

// Drawing code

self.textContainerInset=UIEdgeInsetsMake(10,0,0,0);//这里自定义

UIEdgeInsets insets =self.textContainerInset;

if(self.text.length==0&&self.placeHolder) {

CGRectr =CGRectMake(rect.origin.x+ insets.left+6, rect.origin.y+ insets.top, rect.size.width-insets.left-insets.right, rect.size.height-insets.top-insets.bottom);

if(self.placeHolderFont==nil) {

self.placeHolderFont=self.font;

}

if(self.placeHolderColor==nil) {

self.placeHolderColor= [UIColor lightGrayColor];

}

[self.placeHolder drawInRect:rwithAttributes:@{NSForegroundColorAttributeName:self.placeHolderColor,NSFontAttributeName:self.placeHolderFont}];

return;

}

[superdrawRect:rect];

}

- (void)textChange:(NSNotification*)notify{

[self setNeedsDisplay];

}

- (void)dealloc{

[self removeNotify];

}

@end


效果图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容