键盘出现时向上移动视图

时间:2014-03-12 11:44:21

标签: ios iphone

我是iPhone开发的新手。此代码用于将数据保存在UITextFieldcoredata(供应商)中,并使用UIPicker设置货币UITextField(currencyArray是选择器的内容)。但在输入时我无法在UITextField下方看到,因为键盘会隐藏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;
    }

4 个答案:

答案 0 :(得分:1)

实施包含多个输入字段的表单的更好策略是将所有视图添加到UIScrollView

然后,只要控件覆盖屏幕的一部分,如键盘选择器,您就可以更改滚动视图的大小以匹配可用空间。

完成上述操作后,请致电setContentOffset:animated:以关注您想要显示的视图。

检查this SO post了解详情。

答案 1 :(得分:1)

将此代码放在视图控制器中..

委托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...
}

答案 2 :(得分:0)

//现在将视图作为输入附件视图添加到所选文本字段。

 [textField setInputAccessoryView:yourview];

答案 3 :(得分:0)

如果您的问题是键盘,请尝试此操作隐藏文本字段contentScrollview是放置所有文本字段的视图。

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

如果您想要在单击文本字段时隐藏键盘,请单击文本字段,该文本字段用于显示选择器操作中的选择器或文本字段委托,其中您点击选择器textfiels写入此

[self.view endEditing:YES]; // this will hide keyboard