Nilesh
Nilesh

Reputation: 71

How to move UITextfield up and down?

I am having a login screen where I want to move the textfield up whenever the user touch esthe textfiled to enter data and to move the textfield down along with the keypad when user touches anywhere on the screen.

I am able to move the textfield up on userinteraction and I can move down the keypad when user touches anywhere on the screen but I am not able to bring back the textfield to its original place.

following is my code: .h file:

#import <UIKit/UIKit.h>
#import "RegistrationForm.h"
#import "sqlite3.h";

@interface VLoginViewController : UIViewController <UITableViewDelegate ,UITableViewDataSource>
{
    NSDictionary *tableContents;

    NSArray *textField;

    UILabel *lblCompanyName;

    UITextField *txtUserName;

    UITextField *txtPass;

    UIButton *btnLogin;

    UIButton *btnSignUp;

    RegistrationForm *registration; 

    NSString *dbPath;

    sqlite3 *loginDB;
}

 @property(nonatomic ,retain) NSDictionary *tableContents;

 @property(nonatomic ,retain) NSArray *textField;

 @property(nonatomic, retain) IBOutlet UITextField *txtUserName;

 @property(nonatomic ,retain) IBOutlet UITextField *txtPass;

 @property(nonatomic ,retain) UILabel *lblCompanyName;

 @property(nonatomic ,retain) UIButton *btnLogin;

 @property(nonatomic ,retain) UIButton *btnSignUp;

@end

this is my .m file:

//  LoginPage.m
//  MYBusinessCentral
//
//  Created by Bcod Web on 09/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LoginPage.h"
#define kOFFSET_FOR_KEYBOARD 60.0

@implementation LoginPage
@synthesize imgView;
@synthesize tableContents,textField;
@synthesize txtUserName,txtPassword;
@synthesize btn_login,btn_registration;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    NSArray *text = [[NSArray alloc]initWithObjects:@"" ,@"" ,nil];
    NSDictionary *textData = [[NSDictionary alloc]initWithObjectsAndKeys:text,@"",nil];
    self.tableContents = textData;
    self.textField = [[self.tableContents allKeys] sortedArrayUsingSelector:@selector(compare:)];

    btn_login = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn_login.frame = CGRectMake(25, 260, 270, 40);
    [btn_login setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [btn_login setTitle:@"login" forState:UIControlStateNormal];
    [btn_login addTarget:self action:@selector(Login:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn_login];

    [super viewDidLoad];
}

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    if ([sender isEqual:txtUserName] && [sender isEqual:txtPassword])
    {
        //move the main view, so that the keyboard does not hide it.
        if  (self.view.frame.origin.y >= 0)
        {
            //[self setViewMovedUp:YES];
        }
    }
}

-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5]; // if you want to slide up the view

    CGRect rect = self.view.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.view.frame = rect;

    [UIView commitAnimations];
}

- (void)keyboardWillShow:(NSNotification *)notif
{
    //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately

    if ([txtUserName isFirstResponder] && self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }

    else if ([txtPassword isFirstResponder] && self.view.frame.origin.y >=0)
    {
        [self setViewMovedUp:YES];
    }
}

-(void)textFieldShouldReturn:(UITextField *)sender
{
    if ([sender isEqual:txtUserName] && [sender isEqual:txtPassword]) 
    {
        if (self.view.frame.origin.y <=0) 
        {
            //[self setViewMovedDown:YES];
        }
    }
}

-(void)setViewMovedDown:(BOOL)movedDown
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5]; // if you want to slide up the view

    CGRect rect = self.view.frame;
    if (movedDown)
    {
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.view.frame = rect;

    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notif
{
    //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately

    if ([txtUserName isFirstResponder] && self.view.frame.origin.y <= 0)
    {
        [self setViewMovedDown:YES];
    }

    else if ([txtPassword isFirstResponder] && self.view.frame.origin.y <=0)
    {
        [self setViewMovedDown:YES];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification object:self.view.window]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification object:self.view.window]; 
}

- (void)viewWillDisappear:(BOOL)animated
{
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [txtUserName resignFirstResponder];
    [txtPassword resignFirstResponder];

    NSLog(@"Touches began.");
} 

-(NSInteger) numberOfSectionInTableView:(UITableView *)tableView
{
    return[self.textField count];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *lsData =[self.tableContents objectForKey:[self.textField objectAtIndex:section]];
    return [lsData count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *TextCellIdentifier =@"Cell";

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:TextCellIdentifier];

    if (cell==nil)
    {
        cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TextCellIdentifier ] autorelease];
        cell.accessoryType= UITableViewCellAccessoryNone;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }

    if ([indexPath row] ==0)
    {
        txtUserName = [[UITextField alloc]initWithFrame:CGRectMake(12, 0, 250,20)];

        txtUserName.placeholder=@"UserName";
        txtUserName.autocorrectionType =UITextAutocorrectionTypeNo;
        [txtUserName setClearButtonMode:UITextFieldViewModeWhileEditing];
        txtUserName.keyboardType =UIKeyboardTypeEmailAddress;
        txtUserName.textAlignment =UITextAlignmentLeft;
        txtUserName.font=[UIFont fontWithName:@"Helvetica" size:15];
        txtUserName.adjustsFontSizeToFitWidth =YES;
        [txtUserName setEnabled:YES];
        cell.accessoryView =txtUserName;
        //[cell addSubview:txtUserName];
        [txtUserName release];
    }

    if([indexPath row]==1)     
    {
        txtPassword = [[UITextField alloc]initWithFrame:CGRectMake(12, 0, 250,20)];
        txtPassword.placeholder=@"Password";
        txtPassword.secureTextEntry =YES;
        txtPassword.autocorrectionType =UITextAutocorrectionTypeNo;
        [txtPassword setClearButtonMode:UITextFieldViewModeWhileEditing];
        txtPassword.keyboardType =UIKeyboardTypeEmailAddress;
        txtPassword.textAlignment =UITextAlignmentLeft;
        txtUserName.font=[UIFont fontWithName:@"Helvetica" size:15];
        txtPassword.adjustsFontSizeToFitWidth =YES;
        [txtPassword setEnabled:YES];
        cell.accessoryView=txtPassword;     
        //[cell addSubview:txtPass];
        [txtPassword release];
    }   

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(IBAction)Login:(id)sender
{
}

-(IBAction)Registration:(id)sender
{
}

@end

Upvotes: 0

Views: 655

Answers (2)

Anand
Anand

Reputation: 1973

try this way:

set the delegate for textField 1st.

-(void)textFieldDidBeginEditing:(UITextField *)textField {          

[UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.5];
    [textField setFrame:CGRectMake(50,50,100,40)];
    [UIView commitAnimations];

 }

when keyboard return key pressed set the textfield to original position.

-(BOOL)textFieldShouldReturn:(UITextField *)textField {

[UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.5];
    [textField setFrame:CGRectMake(50,200,100,40)];
    [UIView commitAnimations];
}

On touch's

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[textField resignFirstResponder];

[UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:1.5];
        [textField setFrame:CGRectMake(50,200,100,40)];
        [UIView commitAnimations];

 NSLog(@"Touches began."); 

} 

Upvotes: 1

Tendulkar
Tendulkar

Reputation: 5540

There are tow delegate methods you can use for this.

1.-(void)textFieldDidBeginEditing:(UITextField *)textField         
2.-(BOOL)textFieldShouldReturn:(UITextField *)textField 

1.in didbegin editing

  textfield.frame = CGRectMake(0,-10,100,40);

2.in shouldreturn method

  textfield.frame = CGRectMake(0,10,100,40);

Upvotes: 0

Related Questions