INTRODUCTION
Placeholder plays key role in input entry fields as its describe as hint for what user have to write in input. Placeholder is a text that holds information that is for user to understand purpose of text input field.
Setting Placeholder in UITextView – Overview
In UITextField there is already property exist for placeholder and there is no need to create custom codes for placeholder but there is limitation in UITextField that it can allow only one line in text Visibility but sometime in same cases we need to make more lines visible in input methods also like send messages or take reviews and etc.,. So in these cases we have to use UITableView as input item but it does not contain placeholder property. So, we have to create cases codes to make look like it has placeholder.
Solution For Placeholder in UITextView
1. Put UITextView in your UIViewController and then set its constraint as per you want. And in you viewcontroller’s .h file add UITextViewDelegate.
2. Add below Delegates method in .m file of your controller.
- (void)textViewDidBeginEditing:(UITextView *)textView {
NSLog(@"textViewDidBeginEditing:");
textView.backgroundColor = [UIColor greenColor];
}
- (void)textViewDidEndEditing:(UITextView *)textView{
NSLog(@"textViewDidEndEditing:");
}
- (void)textViewDidChange:(UITextView *)textView{
NSLog(@"textViewDidChange:");
}
3. Create outlet for UITextView and connect in your storyboard.
IBOutlet UITextView *txtView;
4. Add below code in you viewDidLoad Method
- (void)viewDidLoad{
[txtView setText:@“Enter Username”];
[txtView setTextColor: [UIColor grayColor]]; // it will make it look like placeholder you can use more light gray colour if you want.
}
5. Add following code in delegate method textDidChange
- (void)textViewDidChange:(UITextView *)textView{
NSLog(@"textViewDidChange:");
if ([textView.text isEqualString:@“Enter Username”]){
return;
} else
if([textView.text isEqualString:@“”]){
[txtView setText:@“Enter Username”];
[txtView setTextColor: [UIColor grayColor]]; // it will make it look like placeholder you can use more light gray colour if you want.
} else {
[txtView setTextColor: [UIColor blackColor]]; // you can set whatever textColor you want.
}