iOS&UITextView中的placeholder屬性

來源:互聯網
上載者:User

標籤:

一看標題,就很屌絲!

的確,系統不給咱們,那咱們就自己弄!

具體步驟:

  1,建立一個類,繼承UITextView.取名ZHHTextView;

  2,在drawRect:中實現placeholder,其中用到通知來監聽text的change.

大概的步驟就著兩步,具體實現,看代碼.<一行代碼解千言>

現在將.m檔案代碼公布如下:

 

#import "ZHHTextView.h"

 

@implementation ZHHTextView

 

- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {

        NSLog(@"%s",__func__);

        //註冊通知.要用到通知的用意:監聽內容的變化

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

    }

    return self;

}

 

- (void)viewTextChange {

    // 執行此方法,系統自動調用drawRect:方法

    [self setNeedsDisplay];

    

    NSLog(@"%s",__func__);

    

}

 

- (void)dealloc {

    //取消通知,你不取消試試,看你的項目會不會崩

    [[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

    

    // 如果有內容,則返回

    if (self.hasText)return;

    

    // 給placeholder添加屬性

    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];

    //這裡最好還是要與self.font同步

    attributes[NSFontAttributeName] = [UIFont systemFontOfSize:15.0];

    attributes[NSForegroundColorAttributeName] = [UIColor grayColor];

    

    // 其實placeholder是畫上去的,既然是畫上去的,必須給定具體的位置與尺寸

    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);

    NSString* placeholder = @"請輸入鴻歌的QQ...";

 

 // 這個方法很經典

    [placeholder drawInRect:placeholderRect withAttributes:attributes];

}

 

 

@end

 

OK了.

 

iOS&UITextView中的placeholder屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.