Objective-C Scroll VIew not working when keyboard

2019-09-15 03:23发布

问题:

Hello I want my backgroundLoginView to move up when keyboard appears. the flow of views are like superView->scrollView->backgroundView->backgroundLoginView->textFeild1(Login Id) and textFeild2(Password) Here are my codes I want when my keyboards appears for Password the backgroundLoginView automatically moves up. MY backgroundLoginView

the problem

//LoginViewController.h
@interface LoginViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIView *backgroundLoginView;
@property (strong, nonatomic) IBOutlet UIView *backgroundView;
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;

@end 
//LoginViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]
                                           initWithTarget:self
                                           action:@selector(hideKeyBoard)];
    [_backgroundView addGestureRecognizer:tapGesture];

    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width, CGRectGetMaxY(_backgroundView.frame));

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
- (void)keyboardWillShow:(NSNotification*)aNotification
{

    CGSize kbSize = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    NSTimeInterval duration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    [UIView animateWithDuration:duration animations:^{
        UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
        [_scrollView setContentInset:edgeInsets];
        [_scrollView setScrollIndicatorInsets:edgeInsets];
    }];
}

- (void)keyboardWillHide:(NSNotification*)aNotification
{

    NSTimeInterval duration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    [UIView animateWithDuration:duration animations:^{
        UIEdgeInsets edgeInsets = UIEdgeInsetsZero;
        [_scrollView setContentInset:edgeInsets];
        [_scrollView setScrollIndicatorInsets:edgeInsets];
    }];
}

回答1:

You could try this:

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

  UITableViewCell *cell = (UITableViewCell *)[textField superview]; 
  NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
  [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; 
  return YES;

}