帶placeholder的textView

注冊(cè)UITextViewTextDidChangeNotification 通知,每次文字改變的時(shí)候會(huì)重新調(diào)用drawRect方法,重新繪制placeholder。

@interface MyTextView : UITextView
/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字的顏色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end

@implementation MyTextView
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
    
    // 當(dāng)UITextView的文字發(fā)生改變時(shí),UITextView自己會(huì)發(fā)出一個(gè)UITextViewTextDidChangeNotification通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
 }
return self;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
 * 監(jiān)聽(tīng)文字改變
 */
- (void)textDidChange
{
    // 重繪(重新調(diào)用)
[self setNeedsDisplay];
}

- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = [placeholder copy];

[self setNeedsDisplay];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
_placeholderColor = placeholderColor;

[self setNeedsDisplay];
}

- (void)setText:(NSString *)text
{
[super setText:text];

// setNeedsDisplay會(huì)在下一個(gè)消息循環(huán)時(shí)刻,調(diào)用drawRect:
[self setNeedsDisplay];
}

  - (void)setFont:(UIFont *)font
{
[super setFont:font];

[self setNeedsDisplay];
}
-(void)drawRect:(CGRect)rect
{
//    如果有文字,就直接返回,不畫(huà)占位文字
  if (self.hasText) return;

// 文字屬性
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
// 畫(huà)文字
CGFloat x = 5;
CGFloat w = rect.size.width - 2 * x;
CGFloat y = 8;
CGFloat h = rect.size.height - 2 * y;
CGRect placeholderRect = CGRectMake(x, y, w, h);
[self.placeholder drawInRect:placeholderRect withAttributes:attrs];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 一種簡(jiǎn)單的方式實(shí)現(xiàn)帶placeholder的textview,網(wǎng)上很多方法可以實(shí)現(xiàn),這是在stackoverflo...
    0x00chen閱讀 441評(píng)論 0 0
  • 效果如下圖所示: 代碼地址:github.com/youminuo/TextView 喜歡的話給個(gè)star吧??
    優(yōu)米諾閱讀 269評(píng)論 0 0
  • *面試心聲:其實(shí)這些題本人都沒(méi)怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個(gè)offer,總結(jié)起來(lái)就是把...
    Dove_iOS閱讀 27,579評(píng)論 30 472
  • 1 基本選擇器 id選擇器根據(jù)id來(lái)匹配元素,示例:$(id)或者$(“#id")。 類選擇器根據(jù)class來(lái)匹...
    靈08_1024閱讀 457評(píng)論 0 0
  • 《明天的你一定感謝今天的自己:時(shí)間掌控術(shù)》,作者是日本人谷本有香。 作者成書(shū)之前,完成了對(duì)超過(guò)1000位世界名人的...
    Fashion極客閱讀 677評(píng)論 0 1

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