如何在Swift 3中偏移文本视图等于键盘的高度? [英] how to offset text view equals height of the keyboard in swift 3?

查看:72
本文介绍了如何在Swift 3中偏移文本视图等于键盘的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中有一个文本视图,我希望当用户点击文本字段时,它向上移动等于键盘的高度,我使用此代码获取键盘的高度,并且它给出了键盘的大小

I have a text view in my project and I want when user tap the text field it moves up equals to the height of the keyboard I used this code for getting height of the keyboard and It gives me the size of the keyboard

static var sizeForOffsetKeyboard = CGFloat()

    var heightKeyboard : CGFloat?
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardShown(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}

func keyboardShown(notification: NSNotification) {
    if let infoKey  = notification.userInfo?[UIKeyboardFrameEndUserInfoKey],
        let rawFrame = (infoKey as AnyObject).cgRectValue {
        let keyboardFrame = view.convert(rawFrame, from: nil)
        self.heightKeyboard = keyboardFrame.size.height

        levelChatViewController.sizeForOffsetKeyboard = heightKeyboard!

        print(levelChatViewController.sizeForOffsetKeyboard)
        // Now is stored in your heightKeyboard variable
    }
}

但是我没有得到结果,textview不会随着键盘的高度向上移动

But I didn't get the result and the textview won't move up with the height of the keyboard

所以这是偏移textview的代码

so here is the codes for offset textview

func textViewDidBeginEditing(_ textView: UITextView) {


   animateViewMoving(up: true, moveValue: levelChatViewController.sizeForOffsetKeyboard)
}

推荐答案

最简单的方法是使用IQKeyboardManagerSwift

Easiest way is to use IQKeyboardManagerSwift

添加广告连播

      pod 'IQKeyboardManagerSwift'

在您的AppDelegate中

In your AppDelegate

     import IQKeyboardManagerSwift

在didFinishLaunchingWithOptions内部

inside didFinishLaunchingWithOptions

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    IQKeyboardManager.sharedManager().enable = true

     }

这将管理您项目的所有文本,并且您无需在其他任何地方编写内容

This will manage all the text filed of your project and you do not have to write anything anywhere else

一旦爱上它就尝试一下

了解更多信息 https://github.com/hackiftekhar/IQKeyboardManager

这篇关于如何在Swift 3中偏移文本视图等于键盘的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆