有的時(shí)候產(chǎn)品給的需求里面,占位符的顏色大小什么的是有規(guī)定的,這個(gè)時(shí)候我們?cè)趺崔k呢...
一般的設(shè)置占位字符串的代碼如下
self.tf.placeholder = @"hello";
// self.tf.placeholder.backgroundColor = [UIColor redColor];
這個(gè)第二句是直接報(bào)錯(cuò)的,不能更改
那么我們點(diǎn)開占位符的屬性列表,發(fā)現(xiàn)是沒(méi)有辦法更改顏色,底色,大小等屬性的
怎么辦呢
下面提供三種常用的方法來(lái)解決這個(gè)問(wèn)題
帶屬性的占位符
跟帶屬性的字符串一樣,有一個(gè)帶屬性的占位符,替換掉就好了,代碼如下
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSBackgroundColorAttributeName] = [UIColor redColor];
NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"hello" attributes:dict];
self.tf.attributedPlaceholder = string;
這個(gè)方法只能讓所有的占位符達(dá)到一個(gè)效果,只是有簡(jiǎn)單功能
這個(gè)可變字符串的Key值就不一一介紹了,敷個(gè)鏈接上來(lái)
可變的帶屬性的字符串
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSBackgroundColorAttributeName] = [UIColor redColor];
NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"hello" attributes:dict];
self.tf.attributedPlaceholder = string;
這個(gè)還是相對(duì)比較好用的,可以根據(jù)Rang實(shí)現(xiàn)字符串不同區(qū)域不同樣式
重寫textFiled
我們可以自定義一個(gè)自己的tf,然后在xib或者純代碼里面,創(chuàng)建自己寫的tf,然后在tf內(nèi)部進(jìn)行重構(gòu)就可以了
這個(gè)方法最為徹底,基本滿足你任何需求
// 在tf里重寫這個(gè)方法就可以了
- (void)drawPlaceholderInRect:(CGRect)rect
{
[self.placeholder drawInRect:CGRectMake(0, 10, rect.size.width, 0) withAttributes:@{
NSForegroundColorAttributeName : [UIColor redColor],
NSFontAttributeName : self.font}];
}
還有別的方法,比如自己畫一個(gè)占位符,比如放一個(gè)label上去,在點(diǎn)擊的時(shí)候label隱藏,當(dāng)然都比較非主流了,好了,就這些,回家吃飯