web-dev-qa-db-fra.com

Uitableview faire défiler le contenu lorsque le clavier montre

J'ai une vue de table avec un champ de texte et une vue de texte. J'ai implémenté ce code comme suggéré par cet exemple de code Apple https://developer.Apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html

@IBOutlet var myTableView: UITableView
func keyboardWasShown (notification: NSNotification)
{
    println("keyboard was shown")
    var info = notification.userInfo
    var keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size

    myTableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
    myTableView.scrollIndicatorInsets = myTableView.contentInset
}

func keyboardWillBeHidden (notification: NSNotification)
{
    println("keyboard will be hidden")
    myTableView.contentInset = UIEdgeInsetsZero
    myTableView.scrollIndicatorInsets = UIEdgeInsetsZero
}
  override func viewDidLoad() {

    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)

}

Lorsque je clique sur le "texte" de la vue de défilement, allez juste au-dessus du haut de l'écran, mais lorsque je relâche le clavier, il reste défilé. C'est comme si la propriété insets ne pouvait pas être modifiée après la première fois. Quelle est mon erreur?

16
Andorath

Essayez de conserver le chemin d’index d’édition publishingIndexPathObtenir le chemin d’index et faites défiler la vue tabulaire jusqu’au chemin

func keyboardWasShown (notification: NSNotification)
    {
        println("keyboard was shown")
        var info = notification.userInfo
        var keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size

        var contentInsets:UIEdgeInsets

        if UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation) {

            contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
        }
        else {
            contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.width, 0.0);

        }

        myTableView.contentInset = contentInsets

        myTableView.scrollToRowAtIndexPath(editingIndexPath, atScrollPosition: .Top, animated: true)
        myTableView.scrollIndicatorInsets = myTableView.contentInset
    }
13
Yatheesha B L
override func viewDidLoad() {
    super.viewDidLoad()

    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)
    }
}
32
Zany

Utilisez le code ci-dessous pour obtenir Indexpath et modifier le décalage de contenu UITableview en fonction de la hauteur de UIKeyboard

func keyboardWillShow(notification: NSNotification) {
    if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        //self.view.frame.Origin.y -= keyboardSize.height
        var userInfo = notification.userInfo!
        var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        keyboardFrame = self.view.convert(keyboardFrame, from: nil)

        var contentInset:UIEdgeInsets = self.tbl.contentInset
        contentInset.bottom = keyboardFrame.size.height
        self.tbl.contentInset = contentInset

        //get indexpath
        let indexpath = NSIndexPath(forRow: 1, inSection: 0)
        self.tbl.scrollToRowAtIndexPath(indexpath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
    }
}

func keyboardWillHide(notification: NSNotification) {
    if ((notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        let contentInset:UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.tbl.contentInset = contentInset
    }
}
12
Hardik Thakkar

Utilisez cette extension Awesome (mise à jour pour Swift 4.2),

extension UIViewController {

    func registerForKeyboardWillShowNotification(_ scrollView: UIScrollView, usingBlock block: ((CGSize?) -> Void)? = nil) {
        _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil, using: { notification -> Void in
            let userInfo = notification.userInfo!
            let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue.size
            let contentInsets = UIEdgeInsets(top: scrollView.contentInset.top, left: scrollView.contentInset.left, bottom: keyboardSize.height, right: scrollView.contentInset.right)

            scrollView.setContentInsetAndScrollIndicatorInsets(contentInsets)
            block?(keyboardSize)
        })
    }

    func registerForKeyboardWillHideNotification(_ scrollView: UIScrollView, usingBlock block: ((CGSize?) -> Void)? = nil) {
        _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil, using: { notification -> Void in
            let userInfo = notification.userInfo!
            let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue.size
            let contentInsets = UIEdgeInsets(top: scrollView.contentInset.top, left: scrollView.contentInset.left, bottom: 0, right: scrollView.contentInset.right)

            scrollView.setContentInsetAndScrollIndicatorInsets(contentInsets)
            block?(keyboardSize)
        })
    }
}

extension UIScrollView {

    func setContentInsetAndScrollIndicatorInsets(_ edgeInsets: UIEdgeInsets) {
        self.contentInset = edgeInsets
        self.scrollIndicatorInsets = edgeInsets
    }
}

et utiliser comme indiqué ci-dessous à partir du ViewController respectif,

@IBOutlet weak var tableview: UITableView!

override func viewDidLoad() {
        super.viewDidLoad()
        registerForKeyboardWillShowNotification(tableview)
        registerForKeyboardWillHideNotification(tableview)

        /* use the above functions with
           block, in case you want the trigger just after the keyboard
           hide or show which will return you the keyboard size also.
         */

        registerForKeyboardWillShowNotification(tableView) { (keyboardSize) in
            print("size 1 - \(keyboardSize!)")
        }
        registerForKeyboardWillHideNotification(tableView) { (keyboardSize) in
            print("size 2 - \(keyboardSize!)")
        }

    }
11
Soumen

** ne pas faire défiler jusqu'à un spectacle à clavier **

    override func viewDidLoad() {
    super.viewDidLoad()

    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)
    }
}
2
Furkan Vijapura

J'avais une petite idée à ce sujet et j'ai écrit une extension dans Swift . N'hésitez pas à contribuer et à l'utiliser dans vos propres projets:

https://github.com/joluc/AutoAdjust

import Foundation
import UIKit

extension UITableView {
    // I am working on a way to deinit the observers when the tableview also is deiniting.
    // If you have ideas, feel free to help out!
    func setupAutoAdjust()
    {
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardshown), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardhide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    @objc func keyboardshown(_ notification:Notification)
    {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            self.fitContentInset(inset: UIEdgeInsetsMake(0, 0, keyboardSize.height, 0))
        }
    }
    @objc func keyboardhide(_ notification:Notification)
    {
        if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
            self.fitContentInset(inset: .zero)
        }

    }
    func fitContentInset(inset:UIEdgeInsets!)
    {
        self.contentInset = inset
        self.scrollIndicatorInsets = inset
    }
}
0
chronikum
    func keyboardWillShow(notification: NSNotification) {
    if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()) != nil {
        //self.view.frame.Origin.y -= keyboardSize.height
        var userInfo = notification.userInfo!
        var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
        keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)

        var contentInset:UIEdgeInsets = self.tbl.contentInset
        contentInset.bottom = keyboardFrame.size.height
        self.tbl.contentInset = contentInset

        //get indexpath
        let indexpath = NSIndexPath(forRow: 1, inSection: 0)
        self.tbl.scrollToRowAtIndexPath(indexpath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
    }
}

func keyboardWillHide(notification: NSNotification) {
    if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()) != nil {
        let contentInset:UIEdgeInsets = UIEdgeInsetsZero
        self.tbl.contentInset = contentInset
    }
}
0
Aftab Ahmed