最近项目中用到了UITextView,但是又想利用到UITextField中的placeholder占位文字功能,网上搜了一大堆都是自定义UITextView的,感觉不够高大上.后来自己发掘,使用runtime可以直接获取到UITextView的私有方法设置placeholder,方便快捷,下面就说一下怎么用吧
首先还是要导入运行时框架
#import <objc/message.h>
其次,在需要创建带placeholder的UITextView的地方,创建一个富文本
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:@"我是placeholder" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor redColor]}];
然后在调用一下UITextView的私有方法即可
_textView是属性UITextView
((void(*)(id,SEL,NSAttributedString *))objc_msgSend)(_textView,NSSelectorFromString(@"setAttributedPlaceholder:"),attributedString);
占位颜色可以模仿一下UITextField,那么可以通过UITextField的私有方法获取到它的颜色大致是这样的
UIColor* color = ((UIColor* (*)(id,SEL))objc_msgSend)(_textField,NSSelectorFromString(@"_placeholderColor"));
//打印结果
UIExtendedSRGBColorSpace 0 0 0.0980392 0.22
大致为
[UIColor colorWithRed:0 green:0 blue:25/255.0 alpha:0.22]
好了,接下来我们只需要把上面的颜色,大功告成!
[UIColor redColor]
//替换为颜色
[UIColor colorWithRed:0 green:0 blue:25/255.0 alpha:0.22]
如果你不嫌弃长的话,的确是可以两行代码为UITextView加上placeholder的!
注:此方法经过测试只能在iOS 9.0以上机型适用,iOS 8及以下会崩溃
网友评论