IOS scrollView与键盘结合使用--防止遮盖控件

来源:互联网 发布:青岛seo外包公司 编辑:程序博客网 时间:2024/06/05 07:49
<span style="font-family: Arial, Helvetica, sans-serif;">#import "ViewController.h"</span>
@interface ViewController ()@end@implementation ViewController- (void) initScrollView{    // setting contentSize;    self.scrollView.contentSize = CGSizeMake(320, 600);        [self.scrollView setContentOffset:CGPointMake(0, 100) animated:YES];}- (void)viewDidLoad {    [super viewDidLoad];    [self initScrollView];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}- (void) viewWillAppear:(BOOL)animated{    //注册键盘出现通知    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];        //注册键盘隐藏通知    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];        [super viewWillAppear:animated];    }- (void) viewWillDisappear:(BOOL)animated{    //解除键盘出现通知    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];        //解除键盘隐藏通知    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];         [super viewWillDisappear:animated];}- (void) keyboardDidShow:(NSNotification *) notif{    if(keyboardVisiable)    {        return;    }        // 获得键盘尺寸    NSDictionary *info = notif.userInfo;        NSValue *aValue = [info objectForKeyedSubscript:UIKeyboardFrameEndUserInfoKey];    CGSize keyboardSize = [aValue CGRectValue].size;        //重新定义ScrollView的尺寸    CGRect viewFrame = self.scrollView.frame;        viewFrame.size.height -=(keyboardSize.height);  //原来的尺寸减去键盘的高度    self.scrollView.frame = viewFrame;            //获取当前文本框架大小    CGRect textFieldRect = [self.textField frame];        //滚动到当前文本框    [self.scrollView scrollRectToVisible:textFieldRect animated:YES];        keyboardVisiable = YES;    }- (void) keyboardDidHide:(NSNotification *) notif{    // 获得键盘尺寸    NSDictionary *info = notif.userInfo;        NSValue *aValue = [info objectForKeyedSubscript:UIKeyboardFrameEndUserInfoKey];    CGSize keyboardSize = [aValue CGRectValue].size;        //当键盘隐藏的时候,将scrollView重新放下来    CGRect viewFrame = self.scrollView.frame;    viewFrame.size.height += keyboardSize.height;    self.scrollView.frame = viewFrame;        if (!keyboardVisiable) {        return;    }        keyboardVisiable = NO;    }#pragma mark -- UITextFieldDelegate method- (BOOL)textFieldShouldReturn:(UITextField *)textField{    [textField resignFirstResponder];    return YES;}@end


viewControl.h文件:

#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UITextFieldDelegate>{    BOOL keyboardVisiable;}@property(weak,nonatomic) IBOutlet UIScrollView *scrollView;@property (weak, nonatomic) IBOutlet UITextField *textField;@end


0 0
原创粉丝点击