iOS - 根据键盘调整view位置

作者: AlexPei | 来源:发表于2016-06-01 20:59 被阅读656次
  • 效果图
02.gif

#import "ViewController.h"

#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScreenB [UIScreen mainScreen].bounds

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *txtInput;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /** 添加通知 */
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(moveKeyboard:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)moveKeyboard:(NSNotification *)notification{

    /** 键盘完全弹出时间 */
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] intValue];

    /** 动画趋势 */
    int curve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] intValue];
    
    /** 动画执行完毕frame */
    CGRect keyboard_frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    /** 获取键盘y值 */
    CGFloat keyboard_y = keyboard_frame.origin.y;
    
    /** view上平移的值 */
    CGFloat offset = kScreenH - keyboard_y;

    /** 执行动画  */
    [UIView animateWithDuration:duration animations:^{
       
        [UIView setAnimationCurve:curve];
        self.view.transform = CGAffineTransformMakeTranslation(0, -offset);
    }];
    
}

//移除通知
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

知识点:通过通知监听键盘弹出,获取键盘弹出后的frame,以及完全弹出执行动画的时间--duration,以及动画的趋势curve.最后算出要平移的距离offset即可.

相关文章

网友评论

    本文标题:iOS - 根据键盘调整view位置

    本文链接:https://www.haomeiwen.com/subject/ypwhdttx.html