I have a simple browser view controller used as part of a storyboard. It starts out looking great. My UIToolBar is anchored to the bottom of the UIView via a Vertical Space constraint of 0.
When you hit something on the webpage that brings up the keyboard. The UIToolBar is hidden. So I added a listener for the keyboard visibility change and adjusted the constraint based on the height of the keyboard. This seems to work well.
However, if the user then hits the minimize button on the keyboard, the keyboard doesn't totally go away. The top bar of arrow keys to allow for tabbing between input fields (I don't know what to call it) will remain visible. So I cannot set my constraint back to 0, I have to set it again based on the height of the visible keyboard (which I would think would include that top bar).
However when my UIKeyboardDidHideNotification fires, the keyboard height is still the same so I end up like this.
My logic for moving the constraint is based on acquiring the keyboard height this way:
// get height of visible keyboard
NSDictionary* keyboardInfo = [aNotification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
_toolbarBottomVerticalSpaceConstraint.constant = -1 * keyboardFrameBeginRect.size.height;
Is UIKeyboardFrameBeginUserInfoKey not the based value to use in the case of the keyboard being hidden?
The entire source for this view controller is actually really simple at the moment so I'll include all of it in case someone asks for it later.
#import "LEPopupBrowserViewController.h"
#interface LEPopupBrowserViewController ()
#property (weak, nonatomic) IBOutlet UIWebView *webView;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolbarBottomVerticalSpaceConstraint;
#end
#implementation LEPopupBrowserViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
if (_url != nil) {
NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
[_webView loadRequest:request];
}
}
- (void) viewDidUnload {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWillShow:(NSNotification*)aNotification
{
// get height of visible keyboard
NSDictionary* keyboardInfo = [aNotification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
_toolbarBottomVerticalSpaceConstraint.constant = -1 * keyboardFrameBeginRect.size.height;
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardDidHide:(NSNotification*)aNotification
{
// get height of visible keyboard
NSDictionary* keyboardInfo = [aNotification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
_toolbarBottomVerticalSpaceConstraint.constant = -1 * keyboardFrameBeginRect.size.height;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)doneButtonPressed:(id)sender {
// close keyboard if present
[self.view endEditing:YES];
// dismiss ourselves
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Update
I found through some additional research it appears this additional view is called the accessoryView. I see lots of posts of people trying to remove it but haven't found anything where you could find it's height easily. The bothersome part about removing it to me is it seems Apple may reject your app.
Related
Apologies for this basic question, I am new to iOS development. I have a UITextField in a View with AutoLayout that I would like to use to key in messages for a chat system. However when the keypad is displayed it hides the View containing the UITextField (the entire View is behind the keypad).
What should be done to move the View along with the keypad when the keypad transitions from the bottom? The UIView should be back in its original position (at the bottom of the screen) when the keypad is dismissed. My entire UI has been designed with AutoLayout in Storyboard.
Edit:
I looked up How do I scroll the UIScrollView when the keyboard appears? for a solution however there doesn't seem to be any indication AutoLayout has been used along constraints in this answer. How can the same be achieved using AutoLayout in Storyboard. Again, apologies for any lack of understanding as I am very new to iOS development.
Add a UIScrollView to your view controller and keep your UITextField over scrollview.
add UITextFieldDelegate
yourTextField.delegate = self;
you can set content offset of scrollview when touch on UITextField and reposition it to (0, 0) when keyboard resign.
-(void)viewWillAppear:(BOOL)animated
{
yourScrollView.contentSize = CGSizeMake(320, 500);
[super viewWillAppear:YES];
}
-(void)textFieldDidBeginEditing:(FMTextField *)textField
{
[yourScrollView setContentOffset:CGPointMake(0,textField.center.y-140) animated:YES];//you can set your y cordinate as your req also
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
[yourScrollView setContentOffset:CGPointMake(0,0) animated:YES];
return YES;
}
This is what I did recently, may be it helps.
All my fields are inside a wrapper view with a top constraint. Since for me moving the wrapper view a few pixels up and down was enough I use this approach.
Here is an example with a scroll view.
I use a IBOutlet to reference this constraint
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//register for keyboard notifications
_keyboardIsShowing = NO;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
Then on the notification methods
#pragma mark - Keyboard notifications methods
- (void)keyboardWillShow:(NSNotification *) notification{
if (!_keyboardIsShowing) {
_keyboardIsShowing = YES;
[UIView animateWithDuration:0.4 animations:^{
//here update the top constraint to some new value
_topConstraint.constant = _topConstraint.constant - 30;
[self.view layoutIfNeeded];
}];
}
}
- (void)keyboardWillHide:(NSNotification *) notification{
if (_keyboardIsShowing) {
[UIView animateWithDuration:0.4 animations:^{
_topConstraint.constant = _topConstraint.constant + 30;
[self.view layoutIfNeeded];
}];
_keyboardIsShowing = NO;
}
}
There are tons of this kind of answers here on SO.
Good luck.
I have view to type message as shown below.
Now, when I type message, the keyboard appears and the box should move just above keyboard as shown in figure below.
my problem
They keyboard animation and view animation occur at different time. Keyboard appears first and then view appears. Even if i tried to set animation time to any, they occur at different time.
How should I solve my problem?
Please, suggest me way to solve it so that keyboard and view animates to show as if they are of same view. Both animation should occur at exact time so that they look like same view appeared at a time.
what i tried
my view did load has following code
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
now keyboard show function look like
- (void)keyboardWillShow:(NSNotification *)note{
NSDictionary* keyboardInfo = [note userInfo];
CGFloat duration = [[keyboardInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
[UIView animateWithDuration:duration animations:
^{
//chat_typingView is name for typing view
chat_typingView.frame = CGRectMake(chat_typingView.frame.origin.x,
238,
chat_typingView.frame.size.width,
chat_typingView.frame.size.height);
}
maybe you should check if your chat_typinfView is First responder before do the animation and disable Autolayout (very important).
if ([chat_typingView isFirstResponder]) {
// Do the animation
}
PS is recommendable to subscribe to the notification on viewWillApper instead of viewDidLoad
I have a similar setup in one of my apps and I do the following:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardShowed:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
/*** FOR AUTOLAYOUT MODIFICATIONS & ADDITIONS # RUNTIME ***/
self.defaultViewFrame = self.myView.frame
}
- (void) keyboardShowed:(NSNotification*)notification {
//GET KEYBOARD FRAME
CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//CONVERT KEYBOARD FRAME TO MATCH THE OUR COORDINATE SYSTEM (FOR UPSIDEDOWN ROTATION)
CGRect convertedFrame = [self.view convertRect:keyboardFrame fromView:self.view.window];
//..... do something with the convertedFrame (in your case convertedFrame.origin.y)
}
- (void) keyboardHidden:(NSNotification*)notification {
//RESTORE ORIGINAL STATE
[UIView transitionWithView:self.view
duration:.3f
options:UIViewAnimationOptionCurveLinear
animations:^{
self.myView.frame = self.defaultViewFrame;
}
completion:nil];
}
I'm building a project based on the App on the lessons I learned in Apple's "Start Developing iOS Apps Today" documentation. I created a basic View Controller Class with a Text box and two buttons. However, when I started to type the keyboard covered my content.
I have search all over the internet for a clear concise explanation to implementing Apple's sample code provided in there "Moving Content That Is Located Under the Keyboard" section in there development guide:
Listing 5-1 Handling the keyboard notifications
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
[self.scrollView scrollRectToVisible:activeField.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
I received several errors immediately after I import this code into my implementation block of the class:
Use of undeclared identifier 'activeField'
Unknown type name 'scrollView'; did you mean 'UIScrollView'?
Property 'scrollView' not found on object of type 'SignInViewController *'
Following some research and back to basics programming I declared the identifiers in the header file:
UIScrollView *scrollView;
// The UIScrollView class provides support for displaying content that is larger than the size of the application’s window. It enables users to scroll within that content by making swiping gestures, and to zoom in and back from portions of the content by making pinching gestures.
UITextField *activeField;
// A UITextField object is a control that displays editable text and sends an action message to a target object when the user presses the return button. You typically use this class to gather small amounts of text from the user and perform some immediate action, such as a search operation, based on that text.
Also, I declared the property "scollView" for the object of type "SignInViewController" in the interface block of the class:
#property(nonatomic, readonly, retain) UIScrollView *scrollView;
All of the compiling errors cleared.
Unfortunately, following compiling and building this code the content located underneath my keyboard did not move. What did I do incorrectly in writing this code? Could you please explain it simply with examples if possible as I'm trying to get up to speed with Object Oriented C.
I'm including the finished code below. Thank you for your help!:
Header File: SignInViewController.h
#import <UIKit/UIKit.h>
#interface SignInViewController : UIViewController
#end
UIScrollView *scrollView;
// The UIScrollView class provides support for displaying content that is larger than the size of the application’s window. It enables users to scroll within that content by making swiping gestures, and to zoom in and back from portions of the content by making pinching gestures.
UITextField *activeField;
// A UITextField object is a control that displays editable text and sends an action message to a target object when the user presses the return button. You typically use this class to gather small amounts of text from the user and perform some immediate action, such as a search operation, based on that text.
Main file: SignInViewController.m
#import "SignInViewController.h"
#interface SignInViewController ()
//Declared property scrollView
#property(nonatomic, readonly, retain) UIScrollView *scrollView;
#end
#implementation SignInViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
// Code to dismiss the keyboard
- (IBAction)dismissKeyboard:(id)sender
{
[activeField resignFirstResponder];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
//Moving Content That Is Located Under the Keyboard
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
// Get the size of the keyboard
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// Adjust the bottom content inset of your scroll view by the keyboard height.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
// Scroll the target text field into view.
// Check if the active text field is under the keyboard. If it isn’t under the keyboard, the scrollview won’t update the content offset. If the active text field is under the keyboard we update the scroll view’s content offset.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
[self.scrollView scrollRectToVisible:activeField.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}
#end
I have a Tableview where the user can enter values into a textField as one of the custom cells
Apple have some documentation about how to adjust view content by repositioning the view clear of the keyboard's vertical dimension ( Here ) but it relies upon one placing that view into a UIScrollView. I cant do this with a tableview.
I could redesign the app so that the entry gets done in a separate detail view using the usual navigation controller, but i'd rather the user not have to perform an extra touch ( and be ferried off into yet another screen ) if possible. I like the idea of doing the deed "right where we are"
so my workaround to have a few extra tableview cells at the bottom containing a %20 or so, normal usage shouldn't register the oddity, as they are only focussed on what is visible.
I'd have to store the spaces in my datasource array and then sort descending, but that's OK
the question is, is this good practice? and even more possibly, could it be against Apple's HIG sufficient for refusal?
UITableView is a subclass of UIScrollView, so should be able to adjust the content and scroll view insets just like in the example you linked.
The way I've solved this issue is to subclass UITableView. Here's what I've done:
// AOTableView.h file
typedef enum
{
AOKeyboardStateUnknown = 0,
AOKeyboardStateShowing,
AOKeyboardStateHidden
} AOKeyboardState;
#import <UIKit/UIKit.h>
#import "AOKeyboardState.h"
#interface AOTableView : UITableView
#property (nonatomic) BOOL observeKeyboardNotifications;
#property (nonatomic) AOKeyboardState keyboardState;
#end
// AOTableView.m file
#import "AOTableView.h"
#interface AOTableView(Private)
#property (nonatomic) CGRect frame0;
- (void)setup;
- (void)keyboardWillShow:(NSNotification *)notification;
- (void)keyboardWillHide:(NSNotification *)notification;
#end
#implementation AOTableView
#pragma mark - Object lifecycle
- (void)awakeFromNib
{
[self setup];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self setup];
}
return self;
}
- (void)setup
{
self.contentSize = self.frame.size;
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
_keyboardState = AOKeyboardStateUnknown;
_frame0 = self.frame;
_observeKeyboardNotifications = NO;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Custom setters
- (void)setObserveKeyboardNotifications:(BOOL)observeKeyboardNotifications
{
if (_observeKeyboardNotifications == observeKeyboardNotifications)
return;
_observeKeyboardNotifications = observeKeyboardNotifications;
if (_observeKeyboardNotifications)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
else
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
}
#pragma mark - UIKeyboard Notifications
- (void)keyboardWillShow:(NSNotification *)notification
{
if (self.keyboardState == AOKeyboardStateShowing)
return;
self.frame0 = self.frame;
self.keyboardState = AOKeyboardStateShowing;
NSDictionary* info = [notification userInfo];
CGRect keyboardFrame = CGRectZero;
[[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
CGRect frame = self.frame0;
frame.size.height = CGRectGetMinY(keyboardFrame) - CGRectGetMinY(frame);
self.frame = frame;
[self scrollToRowAtIndexPath:self.indexPathForSelectedRow atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
[self deselectRowAtIndexPath:self.indexPathForSelectedRow animated:NO];
}
- (void)keyboardWillHide:(NSNotification *)notification
{
if (self.keyboardState == AOKeyboardStateHidden)
return;
self.keyboardState = AOKeyboardStateHidden;
self.frame = self.frame0;
}
#end
After creation (or loading the view from an IBOutlet), you call this method to tell the class to start listening for keyboard notifications:
[tableViewInstance setObserveKeyboardNotifications:YES];
Whenever a user clicks on a cell, it becomes the self.indexPathForSelectedRow cell... so its scrolled to by the AOTableView instance automatically.
For this to work, though, I've had to turn off userInteraction on the UITextField within the cell (otherwise, the device can get confused about if the user is clicking on the cell or on the text field). Instead, when a user selects a cell that has a text field, I tell the text field to the become first responder, like this:
[cell.textField becomeFirstResponder];
I hope this helps.
You don't need the extra cells or anything fancy.
Since your text fields are inside the table view cells, you can use the following:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
UITableViewCell *cell = (UITableViewCell *)textField.superview.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
return YES;
}
This means that the keyboard will scroll appropriately each time a text field becomes first responder. This takes advantage of the table view being a scroll view subclass.
Note that this assumes:
Your (table) view controller is the text fields' delegate.
Your text field is a subview of the cell's content view, not the cell itself.
If the text field is a subview of the cell, the first line of the method above should reference only one superview (i.e., textField.superview).
I have an app where I add a new item to a table view by having the user tap an edit button which shows a textfield cell at the bottom of the table, similar to the built in Notifications app. I need to adjust the table when the keyboard is shown so that it is not obstructed when their are many rows in the table. I am doing this by subscribing to the notification for when the keyboard shows:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector (keyboardDidShow:)
name: UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector (keyboardDidHide:)
name: UIKeyboardDidHideNotification
object:nil];
}
...
...
-(void) keyboardDidShow: (NSNotification *)notif
{
// If keyboard is visible, return
if (self.keyboardVisible)
{
return;
}
// Get the size of the keyboard.
NSDictionary* info = [notif userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
// Adjust the table view by the keyboards height.
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0);
NSIndexPath *path = [NSIndexPath indexPathForRow:self.newsFeeds.count inSection:0];
[self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
self.keyboardVisible = YES;
}
However, the table that I let a user add a row to can also be tapped and a new view is pushed on to the app. This view also has a text view and when the user taps in it and the keyboard shows the first viewcontroller still gets the notification, which causes a crash.
How can I either ignore the notification or get it to not fire when a new view is pushed?
You could add the class as an observer in viewDidAppear and remove it in viewWillDisappear.