键盘操作往往需要添加一个遮盖层,防止点击其他地方导致出错

1,部分声明

@property (nonatomic, strong) UIView *coverView;

@property (nonatomic, strong)UITapGestureRecognizer *sideslipTapGes;

 

 

2实现方法

- (void)showCoverView {

    //_testview:弹出键盘后遮挡的view

    _coverView=[[UIView alloc]init];

    _coverView.frame=CGRectMake(0, 0, 320, 640);

    _coverView.backgroundColor=[UIColor colorWithRed:1.f/255.f green:1.f/255.f blue:1.f/255.f alpha:0.4];

    

    //单击覆盖层手势

    

    

    _sideslipTapGes= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handeTap)];

    [_sideslipTapGes setNumberOfTapsRequired:1];

    

    [_coverView addGestureRecognizer:_sideslipTapGes];

    [self.view addSubview:_coverView];

    _coverView.hidden=YES;

}

/**

 *explain:点击遮盖层

 */

 

-(void)handeTap{

    

[self.view endEditing:YES];

    

}

 

 

#pragma mark- 监听键盘操作

 

- (void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];

    [self registerForKeyboardNotifications];

}

 

 

- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

 

- (void)registerForKeyboardNotifications

{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

}

 

// Called when the UIKeyboardDidShowNotification is sent.

- (void)keyboardWasShown:(NSNotification*)aNotification

{

    _coverView.hidden=NO;

    

}

 

-(void)keyboardWillChangeFrame:(NSNotification*)notification

{

}

 

// Called when the UIKeyboardWillHideNotification is sent

- (void)keyboardWillBeHidden:(NSNotification*)aNotification

{

    _coverView.hidden=YES;

    

   

}

 

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [textField resignFirstResponder];

  

    return YES;

}

posted @ 2015-05-25 16:24  穿山甲随笔-iOS开发  阅读(245)  评论(0编辑  收藏  举报