【问题标题】:iOS (Swift): How to resize the height of an UIWebView when keyboard is/not in useiOS(Swift):如何在使用/不使用键盘时调整 UIWebView 的高度
【发布时间】:2016-05-31 21:30:59
【问题描述】:

我正在尝试为 iOS 构建一个“本机”Webapp,因为我真的不想深入研究 Swift 问题,因为我多年来一直是 Web 开发人员,使用 UIWebView 非常容易走那条路。

但不幸的是,我遇到了 UIWebView 大小的问题。我的目标是在键盘启用/禁用时自动更改 UIWebView 的高度,以便 WebView 只占用屏幕上的可用空间。

iOS 应用程序本身是用 Swift 编码的,我想正确的方法是使用键盘通知(UIKeyboardDidShowNotification、UIKeyboardWillHideNotification)。

非常感谢您的帮助。提前致谢!

【问题讨论】:

    标签: ios swift uiwebview keyboard resize


    【解决方案1】:

    首先,您可以在 viewDidLoad() 方法中的 ViewControllers 中添加此代码

      NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShowFunction:", name: UIKeyboardWillShowNotification, object: nil) //WillShow and not Did ;) The View will run animated and smooth
      NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHideFunction:", name: UIKeyboardWillHideNotification, object: nil)
    

    你应该在你的 webView 上添加 scrollView 背景 然后你应该添加在键盘显示或隐藏时提供的这两个函数,然后你只需更改滚动视图上的插图和偏移量

    func keyboardWillShowFunction(notification: NSNotification) {
       if let userInfo = notification.userInfo {
          if let keyboardSize: CGSize =    userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size {
            let contentInset = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height,  0.0);
            self.scrollView.contentInset = contentInset
            self.scrollView.scrollIndicatorInsets = contentInset
            self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x, 0 + keyboardSize.height)
        }
      }
    }
    
    func keyboardWillHideFunction(notification: NSNotification) {
       if let userInfo = notification.userInfo {
    
          if let keyboardSize: CGSize =  userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size {
           let contentInset = UIEdgeInsetsZero;
           self.scrollView.contentInset = contentInset
           self.scrollView.scrollIndicatorInsets = contentInset
           self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x, self.scrollView.contentOffset.y)
    
          }
       }
    }
    

    【讨论】:

    • Heya 感谢您到目前为止的帮助。我尝试了上面的代码,但它的编写方式不起作用:zetaneon.net/share/download/XCode.png 所有这些“自我”语句都指向现在的位置(我想我只是为了正确实现它而转储)。当然,我已经在使用代码并尝试使用“webView”更改所有“self”语句。这已经产生了一些影响,但只会在选择输入时使 UIWebView “弹起”一点。除此之外,WebView 的大小保持不变。再次感谢;)
    • 作为附加信息,因为这可能是一个问题:WebView 具有整个屏幕的大小。这是通过与所有边的距离为 0 的约束来完成的。
    猜你喜欢
    • 2014-10-18
    • 1970-01-01
    • 2019-01-17
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2013-04-17
    相关资源
    最近更新 更多