iOS開發中利用runtime設定UITextView的預設文字

樑森森發表於2017-07-17

大家都知道UITextField有一個屬性placeholder是用來設定預設文字的,但不知道大家知不知道UITextView也有一個類似的屬性是可以用來設定預設文字的(反正在今天之前我是不知道的)。之前在專案中也遇到過設定UITextView的預設文字的功能,當初的做法是在UITextView上新增一個UILabel,讓UILabel來顯示UITextView的預設文字。今天在看別人的部落格的時候發現了UITextField有一個placeholderLabel的屬性,這個屬性是UITextView的私有屬性,我們可以通過runtime訪問該屬性。我們可以通過建立一個UILabel,然後利用KVC將UITextView的placeholderLabel替換成我們自己建立的UILabel來達到設定UITextView預設文字的功能。程式碼:

_textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, 200)];

    _textView.delegate = self;

    _textView.tintColor = [UIColor blueColor];

    _textView.font = [UIFont systemFontOfSize:15.f];

    _textView.backgroundColor =[UIColor grayColor];

    [self.view addSubview:_textView];


    

    UILabel *placeholderLabel = [[UILabel alloc] init];

    placeholderLabel.text = @"這是預設文字。。。";

    placeholderLabel.font = [UIFont systemFontOfSize:15.f];

    placeholderLabel.textColor = [UIColor whiteColor];

    placeholderLabel.numberOfLines = 0;

    [placeholderLabel sizeToFit];

    [_textView addSubview:placeholderLabel];

    

    [_textView setValue:placeholderLabel forKey:@"_placeholderLabel"];


如果對UITextView的預設文字要求不是很苛刻的話,這樣就可以快速的設定UITextView的預設文字,可以提高我們的開發效率。

好了,本篇部落格就到此結束了。

相關文章