I would like to slide-up current view when UITextField has tapped cause of keyboard overlaps over textfield.
In same view-controller , It's too easy to handle it but I am using 2 view controller, 1st has header and footer part, 2nd has tableView and some custom cell (like comment field). When tapping comment field , Main View Controller should be slide up ( which has header and footer part ).
I am using in MainViewcontroller ( which should be slide-up)
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
const int movementDistance = 160; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: #"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.wizardQuestionView.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
In subViewController ( MainViewController's tableView's custom cell view )
In header file , I added UITextFieldDelegate
and .m file
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if(textField.tag == 1)
{
NSLog(#"Comment View");
MainViewController *mc = [[MainViewController alloc] init];
//It's going Main ViewController 's method
[mc animateTextField: textField up: YES];
}
}
Any help would be appreciate .
Regards
Onder
Your MainViewController needs to be the delegate of your SubViewController.
Then, when the textField is pressed you need to comunicate that to your delegate. Like this:
if([self.delegate respondsToSelector(#selector(textDidBeginEditing:)])
[self.delegate textDidBeginEditing:textField];
For this you need to define a protocol:
#protocol SubViewControllerProtocol<NSObject>
-(void) textDidBeginEditing:(UITextField*) textField;
#end
and in your SubViewController you need to create the delegate:
#property (nonatomic, weak) id<SubViewControllerProtocol> delegate;
Then in your MainViewController you need to set the delegate:
self.subViewController.delegate = self;
Then, in your MainViewController implement the textDidBeginEditing:
-(void) textDidBeginEditing:(UITextField*) textField {
[self animateTextField: textField up: YES]
}
Related
How would one present a UIViewController (from Storyboard say) that is modal, and slides up from the bottom of the presenting view controller. Requirements would be:
slides up from bottom, with widths aligning with the width of the presenting view controller
does NOT take up whole screen or whole parent presenting view controller (rather only is as high as required to show itself)
can be shown within the context of a view controller which doesn't take the whole screen
I do not use storyboards so I wrote it all out. You can copy paste this into a brand new project and run it to see it working.
Your PresentingController needs to conform to two things. The first protocol is: UIViewControllerTransitioningDelegate which allows the controller to provide a custom presenter (namely itself in our case below). Whatever you return here (be it self, or some other object) needs to conform to UIViewControllerAnimatedTransitioning and provide the custom animations. For this self-contained example, I chose the current viewController to be the presenter and animator.
Next, it needs to conform to protocol: UIViewControllerAnimatedTransitioning which provides the custom animation for any presenting or dismissing controllers.
In other words, when we present or dismiss a viewController, animateTransition from the UIViewControllerAnimatedTransitioning protocol will be called to determine how the child controller should animate into perspective or dismiss from the view-port.
Example (With Transition Animation):
//
// ViewController.m
// SO
//
// Created by Brandon T on 2017-01-23.
// Copyright © 2017 XIO. All rights reserved.
//
#import "ViewController.h"
//Some view controller that will be presented modally.
//I have coloured it red.
#interface ModalController : UIViewController
#end
#implementation ModalController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
}
#end
//The view controller that will present or dismiss some other view controller modally.
//I have coloured it white.
#interface ViewController () <UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning>
#property (nonatomic, assign) bool presentingModalController;
#property (nonnull, nonatomic, strong) ModalController *modalController;
#property (nonnull, nonatomic, strong) UIButton *button;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//For this example, I add a button to present and dismiss the redViewController.
self.button = [[UIButton alloc] initWithFrame:CGRectMake(15, self.view.center.y - 100, self.view.frame.size.width - 30, 45)];
[self.button setTitle:#"Present" forState:UIControlStateNormal];
[self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.button setBackgroundColor:[UIColor lightGrayColor]];
[self.button.layer setCornerRadius:5.0];
[self.button addTarget:self action:#selector(onButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.button];
//Create the redViewController and set its transitioning delegate to self (this controller will be providing the animation and presenter).
//We also set the style to OverFullScreen because we don't want this controller to disappear.
//When a view controller is presented, the one that presented it usually disappears or gets removed from the hierarchy until the child is dismissed. In the case of alerts, or controllers that need to display OVER the current one, we need to set the modalPresentationStyle.
self.modalController = [[ModalController alloc] init];
self.modalController.transitioningDelegate = self;
self.modalController.modalPresentationStyle = UIModalPresentationOverFullScreen;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)onButtonClicked:(UIButton *)button {
if (self.modalController.view.window == nil) {
[self presentViewController:self.modalController animated:YES completion:nil];
[self.button setTitle:#"Dismiss" forState:UIControlStateNormal];
//not a good idea but meh.. I need to keep this example short.
[self.view.window addSubview:self.button];
}
else {
[self.modalController dismissViewControllerAnimated:YES completion:nil];
[self.button setTitle:#"Present" forState:UIControlStateNormal];
[self.view addSubview:self.button];
}
}
//Custom Animations and Presenters.
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
self.presentingModalController = true; //We are presenting the controller.
return self; //Who is animating it? We are.
}
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
self.presentingModalController = false; //We are dismissing the view controller.
return self; //Who animated it? We did.
}
//How fast should it present? I chose 0.5 seconds.
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext {
return 0.5;
}
//The actual animation code.
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
if (self.presentingModalController) {
//If we are presenting, we need to add the new controller's view as a sub-view.
UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
//We need a starting frame for the animation.
CGRect startingFrame = transitionContext.containerView.bounds;
startingFrame.origin.y = startingFrame.size.height; //Starts from the bottom of the parent.
startingFrame.size.height = 100; //Has a height of 100.
//We need an end frame for the animation.
CGRect finalFrame = transitionContext.containerView.bounds;
finalFrame.origin.y = finalFrame.size.height - 100; //100 from the bottom of the parent.
finalFrame.size.height = 100; //Present with a size of 100 height.
//Add the controller's view as a subview of the context.
[transitionContext.containerView addSubview:toViewController.view];
[toViewController.view setFrame:startingFrame];
//Start animating from "startFrame" --> "endFrame" with 0.5 seconds duration and no delay. I chose easeIn style.
[UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
[toViewController.view setFrame:finalFrame];
} completion:^(BOOL finished) {
//We are finished animating, complete the transition!
[transitionContext completeTransition:YES];
}];
}
else {
//If we are dismissing the view controller, we need to animate it down the screen and then remove its view from the context.
UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
//We only need one frame. This is the first frame. We are animating from "endFrame" --> "startingFrame" (backwards/reverse animation).
CGRect startingFrame = transitionContext.containerView.bounds;
startingFrame.origin.y = startingFrame.size.height; //Starts from the bottom of the parent.
startingFrame.size.height = 100; //Has a height of 100.
//Start the animation with 0.5 seconds duration and I chose easeOut style.
[UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
[fromViewController.view setFrame:startingFrame];
} completion:^(BOOL finished) {
//Remove the view controller's view from the context and complete the transition!
[fromViewController.view removeFromSuperview];
[transitionContext completeTransition:YES];
}];
}
}
#end
Example (Without Transition Animation):
//
// ViewController.m
// SO2
//
// Created by Brandon Thomas on 2017-01-23.
// Copyright © 2017 XIO. All rights reserved.
//
#import "ViewController.h"
#interface ModalController : UIViewController
#end
#implementation ModalController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
}
#end
#interface ViewController ()
#property (nonatomic, assign) bool presentingModalController;
#property (nonnull, nonatomic, strong) ModalController *modalController;
#property (nonnull, nonatomic, strong) UIButton *button;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.button = [[UIButton alloc] initWithFrame:CGRectMake(15, self.view.center.y - 100, self.view.frame.size.width - 30, 45)];
[self.button setTitle:#"Present" forState:UIControlStateNormal];
[self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.button setBackgroundColor:[UIColor lightGrayColor]];
[self.button.layer setCornerRadius:5.0];
[self.button addTarget:self action:#selector(onButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.button];
self.modalController = [[ModalController alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)onButtonClicked:(UIButton *)button {
if (self.modalController.view.window == nil) {
//Present
CGRect startingFrame = self.view.bounds;
startingFrame.origin.y = startingFrame.size.height; //Starts from the bottom of the parent.
startingFrame.size.height = 100; //Has a height of 100.
CGRect finalFrame = self.view.bounds;
finalFrame.origin.y = finalFrame.size.height - 100; //100 from the bottom of the parent.
finalFrame.size.height = 100; //Present with a size of 100 height.
[self.modalController.view setFrame:startingFrame];
[self.modalController willMoveToParentViewController:self];
[self addChildViewController:self.modalController];
[self.view addSubview:self.modalController.view];
[self.modalController didMoveToParentViewController:self];
[UIView animateWithDuration:0.5 animations:^{
[self.modalController.view setFrame:finalFrame];
} completion:^(BOOL finished) {
}];
}
else {
//Dismiss
CGRect startingFrame = self.view.bounds;
startingFrame.origin.y = startingFrame.size.height; //Starts from the bottom of the parent.
startingFrame.size.height = 100; //Has a height of 100.
[UIView animateWithDuration:0.5 animations:^{
[self.modalController.view setFrame:startingFrame];
} completion:^(BOOL finished) {
[self.modalController.view removeFromSuperview];
[self.modalController willMoveToParentViewController:nil];
[self.modalController removeFromParentViewController];
[self.modalController didMoveToParentViewController:nil];
}];
}
}
#end
Check out the Apple documentation for this:
Presenting a View Controller Using Custom Animations
To present a view controller using custom animations, do the following
in an action method of your existing view controllers:
Create the view controller that you want to present. Create your
custom transitioning delegate object and assign it to the view
controller’s transitioningDelegate property. The methods of your
transitioning delegate should create and return your custom animator
objects when asked. Call the
presentViewController:animated:completion: method to present the view
controller. When you call the
presentViewController:animated:completion: method, UIKit initiates the
presentation process. Presentations start during the next run loop
iteration and continue until your custom animator calls the
completeTransition: method. Interactive transitions allow you to
process touch events while the transition is ongoing, but
noninteractive transitions run for the duration specified by the
animator object.
EDIT:
Your alternative option is to create a container with your custom sizes and animate your UIViewController added as a child view of your UIViewController:
[self addChildViewController:content];
content.view.frame = [self frameForContentController];
[self.view addSubview:self.currentClientView];
[content didMoveToParentViewController:self];
Taken from this Thread
I am a beginner to IOS programming (and programming in general) and I simply don't understand why my code does not shift everything on my screen when the keyboard appears on the screen, as I intend it to. Can someone please help me understand what I am missing here?
ViewController.h
#interface ViewController : UIViewController <UITextFieldDelegate> {
}
#property (strong, nonatomic) IBOutlet UITextField *firstRoommateTextField;
#property (strong, nonatomic) IBOutlet UITextField *secondRoommateTextField;
#property (strong, nonatomic) IBOutlet UILabel *calculatedValueLabel;
- (IBAction)calculateButton:(UIButton *)sender;
- (IBAction)textFieldDismiss2:(id)sender;
- (IBAction)textFieldDismiss1:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize firstRoommateTextField = _firstRoommateTextField;
#synthesize secondRoommateTextField = _secondRoommateTextField;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
const int movementDistance = 210; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: #"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField: textField up: YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField: textField up: NO];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
I think you forgot to set the delegate for text field which you can set as
_firstRoommateTextField.delegate = self;
_secondRoommateTextField.delegate = self;
in viewDidLoad
or from storyBoard
ctrl+drag from textField to ViewController (right top just below View Controller scene ) and select delegate .
First check the textfield object is assigned to the delegate..i.e.
_firstRoommateTextField.delegate = self;
_secondRoommateTextField.delegate = self;
and then check your delegate methods are getting called or not.
Finally try this, instead of CGRectOffset, try CGRectMake.
In my viewController, there are two separate "custom views". And the first view has some quit animations, while the second view has some enter animations. The question is how could I change my view in my viewController exactly after the first view's quit animation is done? I have tried the view.hidden property, but it lost both the quit and the enter animations. I also tried to add some animateWithDuration thing and put the switchView method in the completion block, which turned out to fail, too.
Here is the code of my viewController:
#interface PopingViewController ()
#property (nonatomic, retain) HomepageView *homepage;
#property (nonatomic, retain) AboutView *about;
#end
#implementation PopingViewController
- (void)switchView
{
self.homepage = nil;
self.about = [[AboutView alloc] initWithFrame:self.view.frame];
self.about.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.about];
}
- (IBAction)tap:(UITapGestureRecognizer *)sender
{
// the onTouch method basically does some quit animations which take about 1 sec
[self.homepage onTouch:[sender locationInView:self.homepage]];
[self switchView];// it will execute before the animations are finished!
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.homepage = [[HomepageView alloc] initWithFrame:self.view.frame];
self.homepage.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.homepage];
}
Thanks in advance!
If they are just plain UIView subclasses then you could implement the UIView transition with class method transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion on UIView.
So, for your case, you would do it like this,
- (void)switchView
{
self.about = [[AboutView alloc] initWithFrame:self.view.frame];
[self.view insertSubView:about belowSubView:self.homepage];
self.about.backgroundColor = [UIColor whiteColor];
[UIView transitionFromView:self.homepage toView:self.about duration:0.6 options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionShowHideTransitionViews completion:^(BOOL completed){ [self.homePage removeFromSuperView]; }];
}
Otherwise, if you are adding the UIViewController's view to some view then, you would use the UIViewController containment methods. Look at this for further detail http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html#//apple_ref/doc/uid/TP40007457-CH18-SW6
I have this code to hide UIPickerView by default:
- (void)viewDidLoad
{
[super viewDidLoad];
[_memberList setAlpha:0];
}
and this code to show UIPickerView when a button tapped :
- (IBAction)buttonChooseMember {
[UIView animateWithDuration:0.6 delay:0. options:UIViewAnimationOptionCurveEaseInOut animations:^{
[_memberList setAlpha:1];
} completion:nil];
}
and the last thing is this, to hide keyboard when user tap anywhere :
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UIView * txt in self.view.subviews){
if ([txt isKindOfClass:[UITextField class]]) {
[txt resignFirstResponder];
}else if ([txt isKindOfClass:[UIPickerView class]]) {
[UIView animateWithDuration:0.6 delay:0. options:UIViewAnimationOptionCurveEaseInOut animations:^{
[_registerMLMList setAlpha:0];
} completion:nil];
}
}
}
but all of this just give me 'appear' animation, because it's only changing Alpha value from 0 to 1 (and vice versa). not slide-up or slide-down just like iOS keyboard.
I tried to use this animation below to have iOS keyboard look and feel on my UIPickerView :
- (IBAction)hidePicker {
UIPickerView *pickerView = [[UIPickerView alloc] init]; // default frame is set
float pvHeight = pickerView.frame.size.height;
float y = _screen.bounds.size.height - (pvHeight * -2); // the root view of view controller
[UIView animateWithDuration:0.5f delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
self.picker.frame = CGRectMake(0 , y, pickerView.frame.size.width, pvHeight);
} completion:nil];
}
- (IBAction)showPicker {
UIPickerView *pickerView = [[UIPickerView alloc] init]; // default frame is set
float pvHeight = pickerView.frame.size.height;
float y = _screen.bounds.size.height - (pvHeight); // the root view of view controller
[UIView animateWithDuration:0.5f delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
self.picker.frame = CGRectMake(0 , y, pickerView.frame.size.width, pvHeight);
} completion:nil];
}
I like this animation, it looks like iOS keyboard animation, but the problem with this animation is... when my app is loaded, the UIPickerView is already shows up. how to hide it when it loads up for the first time?
thank you.
All UIResponder objects have an inputView property. The inputView of a UIResponder is the view that will be shown in place of the keyboard when the responder becomes the first responder.
So if you want a UIPickerView to show up instead of the keyboard, you could simply do it by making your UIResponder (like a UITextField) have a UIPickerView as its inputView.
(As a caveat: you probably won't want a bare UIPickerView as the inputView, because you also need to account for when the keyboard would change size, like when you rotate. But this is the general idea.)
In viewDidLoad take one boolean variable and set it's value as TRUE and also set the UIPickerView's frame so that UIPickerView is invisible for first time.Based on the boolean value handle the frame animations to show or hide the picker view.
hidepicker and showpicker method idea is good, and the problem of "UIPicker is visible when the app is loaded" can be overcome by just setting the frame of UIPickerView while initiating it to the position such that it should not be visible...after that you can call the showpicker method to show the picker view.
I am creating iPhone app which I show below.
At the end of screen I have text field. I have added a delegate for the same. As it is number pad, I have added button seperately so that when button is clicked, they keyboard is hidden.
Below is the code I have:
.h
#interface SearchViewController : UIViewController<UITextFieldDelegate>
#property (retain, nonatomic) IBOutlet UITextField *textField006;
#property (retain, nonatomic) IBOutlet UIButton *doneButton;
- (IBAction)doneAction:(id)sender;
.m
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSLog(#"textFieldShouldReturn");
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(#"textFieldDidBeginEditing");
// Ensure the relevant text field is visible
CGAffineTransform translation = CGAffineTransformIdentity;
CGRect screenBound = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBound.size;
CGFloat screenHeight = screenSize.height;
if (screenHeight==480 || screenHeight==568) {
translation = CGAffineTransformMakeTranslation(0, -120);
doneButton.hidden = NO;
NSLog(#"line 3");
[UIView beginAnimations:nil context:nil];
self.view.transform = translation;
[UIView commitAnimations];
}
}
- (IBAction)doneAction:(id)sender {
doneButton.hidden = NO;
doneButton.hidden = YES;
[textField006 resignFirstResponder];
[UIView beginAnimations:nil context:nil];
self.view.transform = CGAffineTransformIdentity;
[UIView commitAnimations];
[self.textField006 resignFirstResponder];
}
Why isn't the keyboard hiding? How can I hide it?
Keyboard == Decimal Pad Return key >> Go Auto-enable Return key =
Ticked
Be sure to use endEditing: if it's not currently hiding correctly.
About endEditing:
"endEditing causes the view (or one of its embedded text fields) to resign the
first responder status."
"This method looks at the current view and its subview hierarchy for
the text field that is currently the first responder. If it finds one,
it asks that text field to resign as first responder. If the force
parameter is set to YES, the text field is never even asked; it is
forced to resign."
So, the following should work (inside your button click action method):
[self.view endEditing:YES];
Swift Version of #lifetimes Answer
self.view.endEditing(true)
it worked perfectly for me
You can also make [self.textField006 resignFirstResponder]