键盘弹出和消失View的上下移动效果

来源:互联网 发布:python sha256 编辑:程序博客网 时间:2024/06/05 20:48

#pragma mark 设置textView并在设置view随键盘的移动而移动

-(void)setTextView

{

    [self.myTextView.layersetCornerRadius:5.0];

    //监听键盘弹出

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardDidShow:)name:UIKeyboardWillShowNotificationobject:nil];

    //监听键盘消失

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardDidHidden:)name:UIKeyboardWillHideNotificationobject:nil];

    UIToolbar * topView = [[UIToolbaralloc]initWithFrame:CGRectMake(0,0, 320, 45)];

    [topView setBarStyle:UIBarStyleBlackTranslucent];

    //定义两个flexibleSpacebutton,放在toolBar上,这样完成按钮就会在最右边

    UIBarButtonItem * button1 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:                                       UIBarButtonSystemItemFlexibleSpace target:selfaction:nil];

    

    UIBarButtonItem * button2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:                                       UIBarButtonSystemItemFlexibleSpace target:selfaction:nil];

    //定义完成按钮

    UIBarButtonItem * doneButton = [[UIBarButtonItemalloc]initWithTitle:@"完成"style:UIBarButtonItemStyleDone  target:self action:@selector(resignKeyboard)];

    //toolBar上加上这些按钮

    NSArray * buttonsArray = [NSArrayarrayWithObjects:button1,button2,doneButton,nil];

    [topView setItems:buttonsArray];

    [self.myTextViewsetInputAccessoryView:topView];

}




#pragma mark 隐藏键盘

-(void)resignKeyboard

{   //取消键盘为第一相应者

    [self.myTextViewresignFirstResponder];

}

#pragma mark 键盘弹出View向上移动

-(void)keyboardDidShow:(NSNotification *)notification

{

    

    NSDictionary *userInfo = [notificationuserInfo];

    NSValue *aValue = [userInfoobjectForKey:UIKeyboardFrameEndUserInfoKey];

    CGRect keyboardRect = [aValueCGRectValue];

    int height = keyboardRect.size.height;//获取键盘高度

    

    CGContextRef context =UIGraphicsGetCurrentContext();

    //开始播放动画

    [UIViewbeginAnimations:nilcontext:context];

    [UIViewsetAnimationCurve:UIViewAnimationCurveEaseOut];

    [UIViewsetAnimationDuration:0.3];

    [self.myViewsetFrame:CGRectMake(0,-height,320, 480)];

    

    [UIViewcommitAnimations];

    

}



#pragma mark 键盘消失View向下移动

-(void)keyboardDidHidden:(NSNotification *)notification

{

    

    CGContextRef context =UIGraphicsGetCurrentContext();

    //开始播放动画

    [UIViewbeginAnimations:nilcontext:context];

    [UIViewsetAnimationCurve:UIViewAnimationCurveEaseOut];

    [UIViewsetAnimationDuration:0.3];

    [self.myViewsetFrame:CGRectMake(0,0,320, 480)];

    

    [UIViewcommitAnimations];

    

    

}

0 0