chr*_*s17 0 uiscrollview ios swift swift4
我做了30个文本框,并var scrollview: UIScrollView在viewDidLoad()和我试图拉升整体向上滚动视图时,键盘盖文本框。Delegate的文本字段和scrollview已经设置。此代码(下面向下)有效,并且第一次出现键盘时scrollview会向上移动,但是问题是,当第二次或更多次打开键盘时,scrollview不会向上移动,我一直无法解决问题几个小时。谁能在我的代码中检测到一些错误并给出正确答案?我期待任何帮助!
我写的代码是这样的:
var activeField: UITextField?
func registerForKeyboardNotifications(){
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notificaiton:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func deregisterForKeyboardNotifications(){
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWasShown(notificaiton: NSNotification){
var info = notificaiton.userInfo!
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)
var aRect: CGRect = view.frame
aRect.size.height -= keyboardSize!.height
if let activeField = activeField{
if !aRect.contains(activeField.frame.origin) == true{
scrollview.contentInset = contentInsets
}
}
}
@objc func keyboardWillBeHidden(notification: NSNotification){
view.endEditing(true)
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
activeField = textField
registerForKeyboardNotifications()
return true
}
func textFieldDidEndEditing(_ textField: UITextField){
activeField = nil
deregisterForKeyboardNotifications()
}
Run Code Online (Sandbox Code Playgroud)
朋友请尝试这段代码。希望它也对您有用。我正在使用它,并且效果很好。
override func viewDidLoad(){
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//MARK: Methods to manage keybaord
@objc func keyboardDidShow(notification: NSNotification) {
var info = notification.userInfo
let keyBoardSize = info![UIKeyboardFrameEndUserInfoKey] as! CGRect
scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, keyBoardSize.height, 0.0)
scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, keyBoardSize.height, 0.0)
}
@objc func keyboardDidHide(notification: NSNotification) {
scrollView.contentInset = UIEdgeInsets.zero
scrollView.scrollIndicatorInsets = UIEdgeInsets.zero
}
Run Code Online (Sandbox Code Playgroud)
我已经为Swift 4.0编写了此代码。
| 归档时间: |
|
| 查看次数: |
1608 次 |
| 最近记录: |