我正在尝试为iOS构建一个"本机"Web应用程序,因为我真的不想深入了解Swift问题,因为我多年来一直是Web开发人员,并且使用UIWebView很容易走这条路。
但不幸的是,我对 UIWebView 的大小有问题。我的目标是在键盘被禁用时自动更改 UIWebView 的高度,以便 WebView 仅占用屏幕上的可用空间。
iOS应用程序本身是用Swift编码的,我想正确的方法是使用键盘通知(UIKeyboardDidShowNotification,UIKeyboardWillHideNotification)。
我非常感谢您的帮助。提前感谢!
首先,您可以在 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)
您应该在 Web 视图上添加滚动视图背景然后你应该添加这两个功能,当键盘显示或隐藏时提供,然后你只需更改滚动视图上的内陷和偏移量
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)
}
}
}