美文网首页初见
iOS给UITextView添加placeholder

iOS给UITextView添加placeholder

作者: 大哥陈 | 来源:发表于2016-06-27 20:00 被阅读281次

实现方法:通过监听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

效果图

相关文章

网友评论

    本文标题:iOS给UITextView添加placeholder

    本文链接:https://www.haomeiwen.com/subject/bsozdttx.html