uitextfield是ios開發中用戶交互中重要的一個控件,常被用來做賬號密碼框,輸入信息框等。
觀察效果圖
uitextfield有以下幾種特點:
1.默認占位文字是灰色的
2.當光標點上去時,占位文字變為白色
3.光標是白色的
接下來我們通過不同的方法來解決問題
一.將xib中的uitextfield與代碼關聯
1
2
3
4
5
6
7
8
9
10
11
|
通過nsattributestring方法來更改占位文字的屬性 ( void )viewdidload { [super viewdidload]; // do any additional setup after loading the view from its nib. //文字屬性 nsmutabledictionary *dict = [nsmutabledictionary dictionary]; dict[nsforegroundcolorattributename] = [uicolor graycolor]; //帶有屬性的文字(富文本屬性)nsattributestring nsattributedstring *attr = [[nsattributedstring alloc] initwithstring:@ "手機號" attributes:dict]; self.phonefield.attributedplaceholder = attr; } |
但是這種方法只能做出第一種效果,而且不具有通用性。
二.自定義一個uitextfield的類
重寫它的drawplaceholderinrect方法
1
2
3
4
5
6
|
//畫出占位文字- (void)drawplaceholderinrect:(cgrect)rect { [self.placeholder drawinrect:cgrectmake(0, 13, self.size.width, 25) withattributes:@{ nsforegroundcolorattributename : [uicolor graycolor], nsfontattributename : [uifont systemfontofsize:14] }]; } |
這個方法和上一個方法類似,只能做出第一種效果,但這個具有通用性
三.利用runtime運行時機制
runtime是官方的一套c語言庫
能做出很多底層的操作(比如訪問隱藏的一些成員變量\成員方法)
1
2
3
4
5
6
7
8
9
10
|
( void )initialize { unsigned int count = 0; ivar *ivars = class_copyivarlist([uitextfield class ] , &count); for ( int i = 0; i < count; i++) { //取出成員變量 ivar ivar = *(ivars + i); //打印成員變量名字 ddzlog(@ "%s" ,ivar_getname(ivar)); } } |
利用class_copyivarlist這個c函數,將所有的成員變量打印出來
這樣我們就可以直接通過kvc進行屬性設置了
1
2
3
4
5
|
- ( void )awakefromnib { //修改占位文字顏色 [self setvalue:[uicolor graycolor] forkeypath:@ "_placeholderlabel.textcolor" ]; //設置光標顏色和文字顏色一致 self.tintcolor = self.textcolor; } |
通過這個方法可以完成所有的效果,既具有通用性也簡單
最后一個效果是
在獲得焦點時改變占位文字顏色
在失去焦點時再改回去
1
2
3
4
5
6
7
8
9
10
|
//獲得焦點時 - ( bool )becomefirstresponder { //改變占位文字顏色 [self setvalue:self.textcolor forkeypath:@ "_placeholderlabel.textcolor" ]; return [super becomefirstresponder]; } //失去焦點時 - ( bool )resignfirstresponder { //改變占位文字顏色 [self setvalue:[uicolor graycolor] forkeypath:@ "_placeholderlabel.textcolor" ]; return [super resignfirstresponder]; } |