I'm using a textview and noticed that iOS 7 leaves a top margin by default. See image in the following
I read different posts in which the most common solution is to use:
[textViewTest setContentInset:UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)];
But those insets are just a custom solution for a particular device, textview, font size, and so on. Therefore, there are no specific insets applicable to any solution... even worst, I would have to programmatically define different insets to account for all iOS devices and orientations.
Good news is that I found that whenever the textview becomes the first responder and keyboard is shown on screen, this top margin disappears even after keyboard has gone. By the way, I'm resizing contentInset on UIKeyboardDidShowNotification and UIKeyboardWillHideNotification.
Is there a way to simulate keyboard show and hide? So that content inset disappears as explain above.
I have already tried making textview become first responder and then resign it, but for this approach the user would have to see the whole keyboard show-hide animation.
Thanks in advance!
My code below:
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
if(self.topMarginIsAlreadyResized == NO) {
[self.myTextView becomeFirstResponder]; // Keyboard will show to eliminate top margin when view appears
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)handleKeyboardDidShow:(NSNotification *)notification {
if(self.topMarginIsAlreadyResized == NO) {
self.topMarginIsAlreadyResized = YES; // Once that keyboard has shown when view appears, we should hide it manually
[self.myTextView resignFirstResponder];
}
NSValue *keyboardRectAsObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = CGRectZero;
[keyboardRectAsObject getValue:&keyboardRect];
self.myTextView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, keyboardRect.size.height, 0.0f);
}
- (void)handleKeyboardWillHide:(NSNotification *)notification {
self.myTextView.contentInset = UIEdgeInsetsZero;
}
This happens because yor view controller has set the the property automaticallyAdjustsScrollViewInsets
to YES, if you set it to NO everything will be fine. See this question and the accepted answer for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With