键盘遮挡的处理

.m文件相关方法

@interface DemoViewController ()<UITextFieldDelegate> {
    UITextField * _activeField;  //作为第一响应者的UITextField
    CGRect        _originFrame;  //scrollView的初始frame
}
@end

@implementation DemoViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self registerForKeyboardNotifications]; //注册键盘事件
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.bgScrollView.backgroundColor = [UIColor lightGrayColor];

    _originFrame = self.bgScrollView.frame;  //记录scrollView的初始frame
}

- (void)registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
    _bgScrollView.frame = _originFrame;  //键盘隐藏,复原scrollView的frame为初始值
}

- (void)keyboardWasShown:(NSNotification*)aNotification {
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;  //键盘尺寸,这个在输入中英文的时候是不一样的

    //先将scrollview的frame复原,避免因为键盘中英文切换而造成frame的两次该改变
    self.bgScrollView.frame = _originFrame;
    CGRect scrollViewFrame = self.bgScrollView.frame;
    scrollViewFrame.size.height -= kbSize.height;
    self.bgScrollView.frame = scrollViewFrame;
    
    self.bgScrollView.contentSize = CGSizeMake(320, self.fTxtField.frame.size.height + self.fTxtField.frame.origin.y);
    [_bgScrollView scrollRectToVisible:_activeField.frame animated:YES];
    
}

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    _activeField = textField;
}
- (void) textFieldDidEndEditing:(UITextField *)textField{} - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ([string isEqualToString:@" "]) { [textField resignFirstResponder]; return NO; } return YES; }

界面布局如下:

原文地址:https://www.cnblogs.com/benbenzhu/p/3937278.html