最近項(xiàng)目中用到了UITextView,但是又想利用到UITextField中的placeholder占位文字功能,網(wǎng)上搜了一大堆都是自定義UITextView的,感覺(jué)不夠高大上.后來(lái)自己發(fā)掘,使用runtime可以直接獲取到UITextView的私有方法設(shè)置placeholder,方便快捷,下面就說(shuō)一下怎么用吧
首先還是要導(dǎo)入運(yùn)行時(shí)框架
#import <objc/message.h>
其次,在需要?jiǎng)?chuàng)建帶placeholder的UITextView的地方,創(chuàng)建一個(gè)富文本
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:@"我是placeholder" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor redColor]}];
然后在調(diào)用一下UITextView的私有方法即可
_textView是屬性UITextView
((void(*)(id,SEL,NSAttributedString *))objc_msgSend)(_textView,NSSelectorFromString(@"setAttributedPlaceholder:"),attributedString);
占位顏色可以模仿一下UITextField,那么可以通過(guò)UITextField的私有方法獲取到它的顏色大致是這樣的
UIColor* color = ((UIColor* (*)(id,SEL))objc_msgSend)(_textField,NSSelectorFromString(@"_placeholderColor"));
//打印結(jié)果
UIExtendedSRGBColorSpace 0 0 0.0980392 0.22
大致為
[UIColor colorWithRed:0 green:0 blue:25/255.0 alpha:0.22]
好了,接下來(lái)我們只需要把上面的顏色,大功告成!
[UIColor redColor]
//替換為顏色
[UIColor colorWithRed:0 green:0 blue:25/255.0 alpha:0.22]
如果你不嫌棄長(zhǎng)的話,的確是可以?xún)尚写a為UITextView加上placeholder的!
注:此方法經(jīng)過(guò)測(cè)試只能在iOS 9.0以上機(jī)型適用,iOS 8及以下會(huì)崩潰