Friday, November 7, 2014

IOS 7+ Objective-C move up the text boxes when keyboard appears




Hi Now I am doing Objective-C.So I will be writing notes mostly about objective c.This is not meant for teaching you.It is just notes .

The problem we probably face is  buttons are under the keyboard when the keyboard appears.



The result that we want is like this.



So here is the solution for IOS 7 and 8.
First I put all two text boxes and two buttons in UIView.And I am gonna use auto layout top space to top layout guide.  

I will create layout rule as property in h file and connect with storyboard.



Here is the code.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *verticalspace;


@end


And in .m file we create login box property as customView. 

#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UIView *customView;
@end

@implementation ViewController


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)keyboardWillShow:(NSNotification*)aNotification {
       [UIView animateWithDuration:0.25 animations:^
     {
         if (self.customView.frame.origin.y <=120) {
         }
         else{
         
             self.verticalspace.constant -= 100;
             [self.view layoutIfNeeded];
         }
         
     }completion:^(BOOL finished)
     {
         
     }];
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
    [UIView animateWithDuration:0.25 animations:^
     {
         CGRect newFrame = [self.customView frame];
         newFrame.origin.y -= 50; // tweak here to adjust the moving position
         [self.customView setFrame:newFrame];
         
     }completion:^(BOOL finished)
     {
         
     }];
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end