Uitextfield is an important control in iOS development for user interaction, often used to do account password boxes, input information boxes and so on.
Observation Effect Chart
Uitextfield has the following characteristics:
1. The default placeholder text is gray
2. When the cursor points up, the placeholder text becomes white
3. The cursor is white
Next, we'll solve the problem in a different way.
I. Associating Uitextfield with code in Xib
Change the property
(void) viewdidload {
[super viewdidload] of the placeholder text through the Nsattributestring method;
Do no additional setup after loading the view from its nib.
Literal attributes
nsmutabledictionary *dict = [nsmutabledictionary dictionary];
Dict[nsforegroundcolorattributename] = [Uicolor graycolor];
Text with attributes (Rich Text property) nsattributestring
nsattributedstring *attr = [[Nsattributedstring alloc] initwithstring:@ "mobile number" ATTRIBUTES:DICT];
Self.phoneField.attributedPlaceholder = attr;
But this method can only make the first effect, and is not universal.
Two. Customizing a Uitextfield Class
The Drawplaceholderinrect method of rewriting it
Draw placeholder text-(void) Drawplaceholderinrect: (cgrect) rect {
[Self.placeholder drawinrect:cgrectmake (0, 13, Self.size.width) withattributes:@{
nsforegroundcolorattributename: [Uicolor Graycolor],
Nsfontattributename: [Uifont systemfontofsize:14]
}];
}
This method is similar to the previous method and can only make the first effect, but this is universal
Three. Using the runtime runtime mechanism
Runtime is an official set of C language libraries.
Can do a lot of low-level operations (such as access to some of the hidden member variables \ member methods)
(void) Initialize {
unsigned int count = 0;
Ivar *ivars = Class_copyivarlist ([Uitextfield class], &count);
for (int i = 0; i < count; i++) {
//Remove member variable
Ivar Ivar = * (Ivars + i);
Print member variable name
ddzlog (@ "%s", Ivar_getname (Ivar));
}
Using the C function of Class_copyivarlist, all the member variables are printed
So we can set the property directly through the KVC.
-(void) awakefromnib {
//Modify placeholder text color
[self setvalue:[uicolor graycolor] forkeypath:@ "_ Placeholderlabel.textcolor "]; Set cursor color and text color consistent
Self.tintcolor = Self.textcolor;
}
This method can be used to achieve all the results, both universal and simple
The last effect is
Change placeholder text color when focus is obtained
Change back when you lose focus
When I get focus
-(BOOL) Becomefirstresponder {
//Change placeholder text color
[self SetValue:self.textColor forkeypath:@ _ Placeholderlabel.textcolor "]; return [Super Becomefirstresponder];
}
Lose Focus
-(BOOL) Resignfirstresponder {
//Change placeholder text color
[self setvalue:[uicolor graycolor] forkeypath:@ "_ Placeholderlabel.textcolor "]; return [Super Resignfirstresponder];