scrolling not inside how doesn ios view swift scroll

ios - not - uiscrollview swift programmatically



Scrollview y teclado Swift (8)

Soy nuevo aquí y estoy empezando con Swift para iOS.

Empecé a crear una aplicación simple que realiza algunas operaciones. Pero estoy teniendo problemas cuando aparece el teclado, ocultando uno de mis textFields. Creo que es un problema común e investigué pero no pude encontrar nada que resolviera mi problema. Y quiero utilizar un desplazamiento en lugar de animar el campo de texto para que sea visible.

¡¡¡¡¡Gracias!!!!! (perdón por los errores en inglés)


override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyboardWillShow(_ notification:Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0) } } func keyboardWillHide(_ notification:Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) } }


Puede animar su vista de desplazamiento para centrarse en su UITextField en la apariencia del teclado (es decir, hacer que su campo de texto sea el primero en responder) a través de un desplazamiento de desplazamiento. Aquí hay un par de buenos recursos para comenzar (hay muchos en este sitio):

¿Cómo se mueve programáticamente un UIScrollView para enfocar en un control encima del teclado?

Cómo hacer un scroll automático UIScrollView cuando un UITextField se convierte en un primer respondedor

Además, si simplemente usa una UITableView con su contenido en celdas, cuando el campo de texto se convierte en el primero en responder, el UITableViewController se desplazará automáticamente a la celda del campo de texto (aunque no estoy seguro de que esto sea lo que quiere hacer).


Al leer los enlaces que me enviaste, encontré la manera de hacerlo funcionar, ¡gracias !:

func textFieldDidBeginEditing(textField: UITextField) { if (textField == //your_field) { scrollView.setContentOffset(CGPointMake(0, field_extra.center.y-280), animated: true) callAnimation() viewDidLayoutSubviews() } } func textFieldDidEndEditing(textField: UITextField) { if (textField == //your_field){ scrollView .setContentOffset(CGPointMake(0, 0), animated: true) viewDidLayoutSubviews() } }


En ViewDidLoad, registre las notificaciones:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name:UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide), name:UIKeyboardWillHideNotification, object: nil)

Agregue a continuación métodos de observación que hacen el desplazamiento automático cuando aparece el teclado.

func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func keyboardWillShow(notification:NSNotification){ var userInfo = notification.userInfo! var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue() keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil) var contentInset:UIEdgeInsets = self.scrollView.contentInset contentInset.bottom = keyboardFrame.size.height scrollView.contentInset = contentInset } func keyboardWillHide(notification:NSNotification){ let contentInset:UIEdgeInsets = UIEdgeInsetsZero scrollView.contentInset = contentInset }

EDITAR: esta publicación se actualizó para reflejar las mejores prácticas en Swift 2.2 para los selectores del Objetivo C.


La mejor respuesta para swift 3:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil)

Y entonces:

func keyboardWillShow(notification:NSNotification){ //give room at the bottom of the scroll view, so it doesn''t cover up anything the user needs to tap var userInfo = notification.userInfo! var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue keyboardFrame = self.view.convert(keyboardFrame, from: nil) var contentInset:UIEdgeInsets = self.theScrollView.contentInset contentInset.bottom = keyboardFrame.size.height theScrollView.contentInset = contentInset } func keyboardWillHide(notification:NSNotification){ let contentInset:UIEdgeInsets = UIEdgeInsets.zero theScrollView.contentInset = contentInset }


Una respuesta para Swift 3, basada en la propuesta por Daniel Jones, pero más segura (gracias a la guardia), más concisa y con insertos de indicador de desplazamiento consistentes:

@objc private func keyboardWillBeShown(notification: NSNotification) { guard let keyboardFrameValue = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return } let keyboardFrame = view.convert(keyboardFrameValue.cgRectValue, from: nil) scrollView.contentInset.bottom = keyboardFrame.size.height scrollView.scrollIndicatorInsets = scrollView.contentInset } @objc private func keyboardWillBeHidden() { scrollView.contentInset = .zero scrollView.scrollIndicatorInsets = scrollView.contentInset }


contentInset no funciona para mí, porque quiero que la vista de desplazamiento se mueva hacia arriba sobre el teclado. Entonces uso contentOffset :

func keyboardWillShow(notification:NSNotification) { guard let keyboardFrameValue = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return } let keyboardFrame = view.convert(keyboardFrameValue.cgRectValue, from: nil) scrollView.contentOffset = CGPoint(x:0, y:keyboardFrame.size.height) } func keyboardWillHide(notification:NSNotification) { scrollView.contentOffset = .zero }


Aquí hay una solución completa en Swift 3, que utiliza código de guardia y conciso. Además, el código correcto en el keyboardWillHide que solo restablezca la bottom a 0.

@IBOutlet weak var scrollView: UIScrollView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) registerNotifications() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) unregisterNotifications() } func registerNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil) } func unregisterNotifications() { NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil) } func keyboardWillShow(notification: NSNotification){ guard let keyboardFrame = notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return } scrollView.contentInset.bottom = view.convert(keyboardFrame.cgRectValue, from: nil).size.height + 20 } func keyboardWillHide(notification: NSNotification){ scrollView.contentInset.bottom = 0 }