Swift之键盘事件

前端之家收集整理的这篇文章主要介绍了Swift之键盘事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在IOS开发过程中,监听键盘弹出事件,修改对应的UI改变,会使用户体验更加丰富。

首先直接看代码

        // 监听键盘弹出事件,控制toolbar位置
        NSNotificationCenter.defaultCenter().addObserver(self,selector: "onKeyboardWillChangeFrame:",name: UIKeyboardWillChangeFrameNotification,object: nil);

    /**
    键盘显示隐藏事件监听
    */
    func onKeyboardWillChangeFrame(notification: NSNotification) {
        // 1、将通知中的数据转换成NSDictionary
        let dict = NSDictionary(dictionary: notification.userInfo!);
        // 2、获取键盘最后的Frame值
        let keyboardFrame = dict[UIKeyboardFrameEndUserInfoKey]!.CGRectValue();
        // 3、获取键盘移动值
        let ty = keyboardFrame.origin.y - view.frame.height;
        // 4、获取键盘弹出动画事件
        let duration = dict[UIKeyboardAnimationDurationUserInfoKey] as Double;
        UIView.animateWithDuration(duration,animations: { () -> Void in
//            5、设置整个屏幕随键盘移动
            self.toolbar.transform = CGAffineTransformMakeTranslation(0,ty);
        });

//        键盘弹出隐藏所执行的操作数据
//        UIKeyboardAnimationCurveUserInfoKey = 7;
//        UIKeyboardAnimationDurationUserInfoKey = "0.25";  键盘弹出/隐藏时动画时间
//        UIKeyboardBoundsUserInfoKey = "NSRect: {{0,0},{375,258}}";
//        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5,796}";
//        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5,538}";
//        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0,667},258}}";
//        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0,409},258}}";

    }

    deinit {
        // 控制器销毁时,移除消息通知监听(必须)
        NSNotificationCenter.defaultCenter().removeObserver(self);
    }
原文链接:https://www.f2er.com/swift/327610.html

猜你在找的Swift相关文章