Reputation: 385
I am implementing a textView in my viewController. This textView covers the entire screen since I plan to make this view for users to write down their notes. However, there seems to be a problem when user touches the textview and the keyboard pops up.
The thing is that, once touches the textview, the keyboard shows up half of the screen, and the beginning of the editing text gets hidden behind the keyboard. I tried typing something and didn't see the text at all since the editing text is behind the keyboard. Is there a way to fix this problem?
Upvotes: 3
Views: 1868
Reputation: 7845
You have to resize the text view when the keyboard pops up. First of all, define a new method that register your controller for keyboard show and hide notifications:
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
Then call [self registerForKeyBoardNotifications];
from your viewDidLoad:
method.
After that, you have to implement the callback methods:
Here's keyboardWasShown:
, where you get the keyboard's height and subtract that amount to your textView's frame height (as you said, your text view fills up the entire screen so the final height is the previous height minus the keyboard height):
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGRect rect = self.textView.frame;
rect.size.height -= kbSize.height;
}
And here's keyboardWillBeHidden:
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
CGRect rect = self.textView.frame;
rect.size.height = SCREEN_HEIGHT;
}
Upvotes: 0
Reputation: 809
Write the delegate methods for UITextView in you implementation file and also set delegate of yout UITextView to self
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
CGRect rect = txtMessage.frame;
rect.size.height = 91;// you can set y position according to your convinience
txtMessage.frame = rect;
NSLog(@"texView frame is %@",NSStringFromCGRect(textView.frame));
return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
return YES;
}
- (void)textViewDidEndEditing:(UITextView *)textView{
CGRect rect = txtMessage.frame;
rect.size.height = 276; // set back orignal positions
txtMessage.frame = rect;
NSLog(@"EndTextView frame is %@",NSStringFromCGRect(textView.frame));
}
Upvotes: 2