最近在做一個關於微博的項目,用到了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屬性的值就可以了,顏色、字體大小都可以自定義的哦。希望能幫到看過的朋友!