简体   繁体   中英

scrolling UITableView to bottom in addition to resizing insets

so I have a UITableView that I need to scroll to the very last cell when the keyboard appears. Currently I listen for the UIKeyboardDidShow/Hide notifications and resize the insets to make the whole tableView be above the keyboard, and I attempt to scroll it down. The scrolling works if the tableView is at the very top when the keyboard appears, but if its scrolled somewhere in the middle of the list or at the bottom then it does not scroll all the way down and gets kind of messed up (I cant scroll past a certain point, just kind of janky in general).

Below is my code that runs when the keyboard is shown:

func keyboardShown(notification: NSNotification) {

        // changes the content insets of the tableView to be above the keyboard
        let keyboardSize = notification.userInfo![UIKeyboardFrameBeginUserInfoKey]?.CGRectValue().size

        var contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)

        var rate: NSTimeInterval = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue

        UIView.animateWithDuration(rate, animations: {

            self.commentsTableView.contentInset = contentInsets
            self.commentsTableView.scrollIndicatorInsets = contentInsets

        }, completion: { (value: Bool) in

            // scrolls to bottom
            self.scrollToBottom()

        })

    }

and here is the method that actually does the scrolling:

func scrollToBottom() {

        // scrolls to bottom
        let rect = CGRect(x: 0.0, y: commentsTableView.contentSize.height - commentsTableView.bounds.size.height, width: commentsTableView.bounds.size.width, height: commentsTableView.bounds.size.height)
        commentsTableView.scrollRectToVisible(rect, animated: true)
    }

does anyone know of a better way to accomplish this or see any problems with my current implementation?

I don't recommend you to change contentInset of the table in your case. Instead, change the height of the table, eg when keyboardShown function of your is called, cut the height equal to keyboard's height from your table's height, and when keyboard is gone, do the opposite. Good Luck!

This method works well for me:

NSIndexPath* ipath = [NSIndexPath indexPathForRow: [dataSourceArray count]-1 inSection:0];
[tableView scrollToRowAtIndexPath: ipath atScrollPosition: UITableViewScrollPositionTop animated: YES];

You can play around with with the scroll position to get the effect you're looking for, this tells the table to scroll to the last cell instead of to a specific CGRect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM