ios - 出现键盘时向上移动 View

标签 ios iphone

我是 iPhone 开发新手。此代码用于将 UITextField 中的数据保存到 coredata(Vendor),并使用 UIPicker 设置货币 UITextField(currencyArray 是 picker 的内容) .但是我在输入时看不到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;
    }

最佳答案

将此代码放入您的 View Controller 中..

并委托(delegate)文本域..

//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...
}

关于ios - 出现键盘时向上移动 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22350458/

相关文章:

ios - IOS侧边菜单

c++ - Qt C++ 在 iOS 11.4.1 上隐藏键盘

ios - Swift 后台执行选择器

ios - 在 native react 中动态需要 json 文件(来自数千个文件)

iphone - 如何更新 NSMutableDictionary?

iphone - 在我的应用程序中显示 FaceBook 个人资料

ios - 如何在 Swift 的 ViewController 中显示动态数据

iphone - 选择 UITableView 中的所有单元格,甚至 iOS 中不可见的单元格

iPhone+后台执行选择器

iphone - 将应用程序提交到 itune connect 使用不同的默认语言然后是英语(未找到应用程序记录。)