如何在swift 3中偏移文本视图等于键盘的高度?

时间:2017-08-05 04:18:15

标签: ios swift3 keyboard uitextfield

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

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不会因为键盘的高度而上升

所以这里是偏移文本视图的代码

func textViewDidBeginEditing(_ textView: UITextView) {


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

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用IQKeyboardManagerSwift

添加广告

      pod 'IQKeyboardManagerSwift'

在你的AppDelegate

     import IQKeyboardManagerSwift

在didFinishLaunchingWithOptions中

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

    IQKeyboardManager.sharedManager().enable = true

     }

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

只要你喜欢它就试试吧

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