0

I am new to iPhone development. This code is for saving data in UITextField to coredata(Vendor) and also setting the currency UITextField using UIPicker(currencyArray are the contents of picker). But I cant see below UITextField while entering because keyboard hides the UITextField.

@implementation DetailViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.currencyArray =[[NSArray alloc]initWithObjects:@"$",@"INR",@"EURO" ,nil];
    self.contactPersonTextField.frame = CGRectMake(20, 308, 280, 30);
    self.contactPersonNumberTextField.frame = CGRectMake(20, 341, 280, 30);
    self.mobileNumberTextField.frame = CGRectMake(20, 374, 280, 30);
    self.faxNumberTextField.frame = CGRectMake(20, 407, 280, 30);
    self.emailTextField.frame = CGRectMake(20, 440, 280, 30);
    self.remarksTextField.frame = CGRectMake(20, 473, 280, 30);
    self.statusTextField.frame = CGRectMake(20, 506, 280, 30);
    self.paymentTermsDateTextField.frame = CGRectMake(20, 539, 280, 30);

    self.serialNoTextField.delegate = self;
    self.vendorCodeTextField.delegate = self;
    self.vendorNameTextField.delegate = self;
    self.groupTextField.delegate = self;
    self.currencyTextField.delegate = self;
    self.accountBalanceTextField.delegate = self;
    self.dateOfCreationTextField.delegate = self;
    self.telephone1Textfield.delegate = self;
    self.telephone2TextField.delegate = self;

    self.contactPersonTextField.delegate = self;
    self.contactPersonNumberTextField.delegate = self;
    self.mobileNumberTextField.delegate = self;
    self.faxNumberTextField.delegate = self;
    self.emailTextField.delegate = self;
    self.remarksTextField.delegate = self;
    self.statusTextField.delegate = self;
    self.paymentTermsDateTextField.delegate = self;


    //setting frame for text field in scroll view

    AppDelegate* appDelegate  = [UIApplication sharedApplication].delegate;
    self.managedObjectContext2 = appDelegate.managedObjectContext;
    [self.scrollView setContentSize:CGSizeMake(self.view.frame.size.width,600)];

    //[self.serialNoTextField setPlaceholder:[self.textfieldArray objectAtIndex:0]];
    /*  if ([[self.textfieldArray objectAtIndex:0] isEqualToString:@"Vendor Code"]) {
            appDelegate.vendorCode++;
            self.vendorCodeTextField.text = [NSString stringWithFormat:@"VC00%i",appDelegate.vendorCode];

    }
    */
    // Fetching Records and saving it in "fetchedRecordsArray" object
    self.fetchedRecordsArray2 = [appDelegate getAllVendorRecords];
    // Do any additional setup after loading the view, typically from a nib.

}

-(void)settextFieldTitle:(NSArray *)titles
{
    self.textfieldArray =[[NSMutableArray alloc]init];
    self.textfieldArray = titles;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)returnActionOnTextfield:(id)sender
{

    [self.paymentTermsDateTextField resignFirstResponder];

}

- (IBAction)addPhoneBookEntry:(id)sender
{

    // Add Entry to PhoneBook Data base and reset all fields

    //  1
    Vendor * newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Vendor"
                                                              inManagedObjectContext:self.managedObjectContext2];
    //  2
    newEntry.serialNo = self.serialNoTextField.text;
    newEntry.vendorCode = self.vendorCodeTextField.text;
    newEntry.vendorName = self.vendorNameTextField.text;

    //  6

    newEntry.group = self.groupTextField.text;

    //  7

    newEntry.currency  = self.currencyTextField.text;
    newEntry.accountBalance = self.accountBalanceTextField.text;
    newEntry.dateOfCreation = SYSTEM_CLOCK;
    newEntry.telephone1 = self.telephone1Textfield.text;
    newEntry.telephone2 = self.telephone1Textfield.text;
    newEntry.contactPerson = self.contactPersonTextField.text;
    newEntry.contactPerson = self.contactPersonTextField.text;

    newEntry.contactPersonNumber = self.contactPersonNumberTextField.text;

    newEntry.mobileNumber = self.mobileNumberTextField.text;
    newEntry.faxNumber = self.faxNumberTextField.text;
    newEntry.email = self.emailTextField.text;
    newEntry.remarks = self.remarksTextField.text;
    newEntry.status = self.statusTextField.text;
    newEntry.paymentTermsDate  = SYSTEM_CLOCK;


    //  8
    NSLog(@"%@",newEntry.serialNo);

    //  3
    NSError *error;
    if (![self.managedObjectContext2 save:&error])
    {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
    //  4
    self.serialNoTextField.text = @"";
    self.vendoeCodeTextField.text = @"";
    self.vendorNameTextField.text = @"";
    self.groupTextField.text = @"";
    self.currencyTextField.text = @"";
    self.accountBalanceTextField.text = @"";
    self.dateOfCreationTextField.text = @"";
    self.telepone1Textfield.text = @"";
    self.telephone2TextField.text = @"";
    self.contactPersonTextField.text = @"";
    self.contactPersonNumberTextField.text = @"";
    self.mobileNumberTextField.text = @"";
    self.faxNumberTextField.text = @"";
    self.emailTextField.text = @"";
    self.remarksTextField.text = @"";
    self.statusTextField.text = @"";
    self.paymentTermsDateTextField.text = @"";
    //  5
    [self.view endEditing:YES];
    UIAlertView *view =[[UIAlertView alloc]initWithTitle:@"Added" message:@"Your contacts has been added" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [view show];


}

- (IBAction)showPhoneBook:(id)sender
{

}


-(void)keyboardWillShow 
{
    // Animate the current view out of the way
    if (self.scrollView.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.scrollView.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)keyboardWillHide 
{
        if (self.scrollView.frame.origin.y >= 0)
        {
            [self setViewMovedUp:YES];
        }
        else if (self.scrollView.frame.origin.y < 0)
        {
            [self setViewMovedUp:NO];
        }
}

    -(void)textFieldDidBeginEditing:(UITextField *)sender


    {

        if ([sender isEqual:self.serialNoTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:NO];
            }
        }
        else if ([sender isEqual:self.vendoeCodeTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.vendorNameTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.groupTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >=0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.currencyTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.accountBalanceTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.dateOfCreationTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.telepone1Textfield])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.telephone2TextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.contactPersonTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.contactPersonNumberTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.mobileNumberTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.faxNumberTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.emailTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.remarksTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.statusTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >=0)
            {
                [self setViewMovedUp:YES];
            }
        }
        else if ([sender isEqual:self.paymentTermsDateTextField])
        {
            //move the main view, so that the keyboard does not hide it.
            if  (self.scrollView.frame.origin.y >= 0)
            {
                [self setViewMovedUp:YES];
            }
        }

    }

    //method to move the view up/down whenever the keyboard is shown/dismissed
    -(void)setViewMovedUp:(BOOL)movedUp
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3]; // if you want to slide up the view

        CGRect rect = self.scrollView.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.scrollView.frame = rect;

        [UIView commitAnimations];
    }


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

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

    - (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];
    }

    #pragma  mark - UITextfield Delegate
    - (BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        return YES;
    }
    - (IBAction)pickerViewPressed:(id)sender {

        AppDelegate* appDelegate  = [UIApplication sharedApplication].delegate;
        self.managedObjectContext2 = appDelegate.managedObjectContext;
        self.fetchedRecordsArray2 = [appDelegate getAllVendorRecords];
        myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 100, 320, 200)];
        myPickerView.delegate = self;
        myPickerView.showsSelectionIndicator = YES;
        [self.view addSubview:myPickerView];



    }

    - (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component {

       NSString *currency = [self.currencyArray objectAtIndex:row];
        [self.currencyTextField setText:currency ];
        [pickerView removeFromSuperview];
    }

    // tell the picker how many rows are available for a given component
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
        NSUInteger numRows = [self.currencyArray count];
      //  NSLog(@"%@",self.currencyArray.count);

        return numRows;
    }

    // tell the picker how many components it will have
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
        return 1;
    }

    // tell the picker the title for a given component
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {


        //Vendor * selectCurrency = [self.currencyArray objectAtIndex:row];
         NSLog(@"%@",self.currencyArray);
         NSString *title;
        title = [self.currencyArray objectAtIndex:row];
        return title;



    }

    // tell the picker the width of each row for a given component
    - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
        int sectionWidth = 300;

        return sectionWidth;
    }
Marcus S. Zarra
  • 46,143
  • 9
  • 99
  • 181

4 Answers4

1

A better strategy of implementing a form with several input fields would be to add all of the views into a UIScrollView.

Then whenever a control covers part of the screen like a keyboard or a picker - you can change the size of the scrollview to match the available space.

Once you've done that, call setContentOffset:animated: to focus on the view you want to be visible.

Check this SO post to learn more.

Community
  • 1
  • 1
Tom Susel
  • 3,111
  • 1
  • 22
  • 23
1

Put this code in your view controller..

And delegate the textfiled..

//text field or keyboard method start
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
- (int)extracted_method:(CGFloat)heightFraction
{
    return heightFraction < 0.0;
}

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


    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];

    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;

    if([self extracted_method:heightFraction])
    {
        heightFraction = 0.0;
    }
    else if(heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

    if(orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown){

        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);

    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textView
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}
-(BOOL)textFieldShouldReturn:(UITextField * )textField
{
    // [TitleOfPosting resignFirstResponder];
    [textField resignFirstResponder];

    return YES;
    // Do the search...
}
Ashish Kakkad
  • 22,149
  • 11
  • 88
  • 130
0

// Now add the view as an input accessory view to the selected textfield.

 [textField setInputAccessoryView:yourview];
Rushabh
  • 3,125
  • 4
  • 25
  • 49
0

Try This if your issue is keyboard hides the textfield here contentScrollview is the view where all text fields are placed.

-(void)textFieldDidEndEditing:(UITextField *)textField
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
[contentScrollview setFrame:CGRectMake(0.0,100,1024,566)];// you can change 100.0 according to your requirement you can also take a global variable 
[UIView commitAnimations];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
[contentScrollview setFrame:CGRectMake(0.0,-150.0,1024,566)];// you can change -150.0 according to your requirement 
[UIView commitAnimations];
}

Try this if you want to hide keyboard when you click on textfield which is used to show picker in picker action or textfield delegate where you tap on the picker textfiels write this

[self.view endEditing:YES]; // this will hide keyboard
Charan Giri
  • 1,097
  • 1
  • 9
  • 15