Xcode / Swift在键盘打开时调整UIWebView的大小

时间:2018-08-10 07:06:49

标签: ios swift xcode uiwebview

好吧,我已经花了几个小时并且可能只是想念它...但是当单击文本字段并打开键盘时,如何调整UIWebView的大小?

现在我正在听键盘,获取所有测量值以调整其大小,然后调整其大小:

keyboardWillShow()

在仿真器中,它完全按预期工作,然后在具有'.trailing'属性的UIButtonBarStackView上显示约束错误后,将其还原。我认为这来自键盘,但是不确定...

有人知道如何解决这个问题,或者在哪里看吗?

我还看到了其他一些问题,并尝试了其他解决方案,但没有任何运气。

2 个答案:

答案 0 :(得分:0)

1)使用此库并尝试。

pod 'IQKeyboardManagerSwift'

答案 1 :(得分:0)

Swift 4.2答案:(虽然不赞成使用webView,但我建议使用wekKitView)

import UIKit
import AVFoundation

class ViewController: UIViewController {

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "https://www.google.com")
    let request = URLRequest(url: url!)
    webView.loadRequest(request)

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(notification:)), name: UIApplication.keyboardWillShowNotification, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: UIApplication.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardHeight = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height {

        webView.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
    }
}

@objc func keyboardWillHideß(notification: NSNotification) {
    UIView.animate(withDuration: 0.2, animations: {
        // For some reason adding inset in keyboardWillShow is animated by itself but removing is not, that's why we have to use animateWithDuration here
        self.webView.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    })
}
}