iOS給UITextView添加placeholder

實(shí)現(xiàn)方法:通過監(jiān)聽UITextView的文本變化,重繪UITextView將placeholder繪制出來。

支持xib實(shí)時(shí)預(yù)覽placeholder效果。


UITextViewWithPlaceHolder.h文件

#import <UIKit/UIKit.h>

//在定義類的前面加上IB_DESIGNABLE宏,實(shí)現(xiàn)控件在xib或storyboard上可以實(shí)時(shí)渲染

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


效果圖
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容