当键盘出现并消失时,Objective-C Scroll VIew无法正常工作

时间:2017-01-06 12:41:33

标签: objective-c uiview uiscrollview keyboard-events

您好我希望我的backgroundLoginView在键盘出现时向上移动。 观点的流动就像 superView-> scrollView-> backgroundView-> backgroundLoginView-> textFeild1(登录ID)和textFeild2(密码) 这是我想要的密码时我想要的密码,backgroundLoginView会自动向上移动。 我的backgroundLoginView

enter image description here

问题

enter image description here

//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 个答案:

答案 0 :(得分:0)

你可以试试这个:

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

}