Today, the project has an interface that needs to be implemented through uitextview and has the placeholder function of uitextfield. I thought it was quite interesting last night and I would like to share it with you.
First put the final effect completion diagram:
The specific idea is to create a uitextview, add a uilable on it, and listen for changes in its content through the uitextview proxy method to determine whether the uilable needs to be hidden.
The Code is as follows:
1 uitextview * textview = [[uitextview alloc] init]; // create a textview2 [self. view addsubview: textview]; // Add it to the interface to be displayed. 3. textview. delegate = self; // sets the textview proxy to facilitate subsequent use of the proxy method to listen for changes in textview content 4 self. textview = textview; // set it to the global variable 5 textview. frame = cgrectmake (10, 20,300,260); // sets the textview of frame6. layer. bordercolor = [uicolor graycolor]. cgcolor; // Add a border to textview. You need to import the textzcore Framework 7 textview. layer. borderwidth = 1; // set the Border width to 8 textview. layer. cornerradius = 5.0f; // set the rounded corner 9 textview. returnkeytype = uireturnkeydone; // you can specify the key content in the lower-right corner of the keyboard.
After creation, you can add a uilable inside textview as placeholder.
1 uilabel * lable = [[uilabel alloc] initwithframe: cgrectmake (5, 5,300, 20)]; // create a lable and set frame2 self. lable = lable; 3 lable. enabled = no; // disable lable to change. You must set 4 lable. TEXT = @ "no more than 200 words, detailing your skills and expertise"; // set the content to 5 lable. font = [uifont systemfontofsize: 13]; // set the font size to 6 lable. textcolor = [uicolor graycolor]; // set the font color to gray 7 lable. backgroundcolor = [uicolor clearcolor]; // clear background color 8 [textview addsubview: lable]; // Add it to uitextview
At this point, we have added a line of lable on the uitextview as the placeholder. To hide it when it is input like uitextfield and display it when there is no content, we also need to call the uitextview proxy method:
-(Void) textviewdidchange :( uitextview *) textview {self. lable. TEXT = textview. text; If (textview. text. length = 0) {self. lable. TEXT = @ "no more than 200 words, detailing your skills and expertise";} else {self. lable. TEXT = @"";}}
Now the custom uitextview has been modeled, but it is still not perfect, because the keyboard cannot exit, you can use the following code:
1 -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text2 {3 if ([text isEqualToString:@"\n"]) {4 [self.textView resignFirstResponder];5 return NO;6 }7 return YES;8 }
Implement placeholder with custom uitextview