DeyaEldeen DeyaEldeen - 1 year ago 79
iOS Question

How to scroll to a specific UITableViewCell top to UITableView top not center? (2 gifs to explain)

this is what I want (cell top become at table top)


this is what is happening (cell top become at table center)


I use this code

let indexPath = NSIndexPath(forRow: 2+numberOfComments, inSection: 0)
self.tableView?.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)

EDIT :- extra info, the target cell is the last cell in the table.

Answer Source
  1. Create a layout constraint for you tableview bottom and container view bottom, name it botMargin and set it equal 0


  1. When the keyboard show, set botMargin.constant = keyboardHeight, and when the keyboard was hidden, set it back to 0

And this is the code to get the height of keyboard

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.onShowKeyboard(_:)), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.onHideKeyboard), name: UIKeyboardDidHideNotification, object: nil) 

func onShowKeyboard(notification:NSNotification) {
    let userInfo:NSDictionary = notification.userInfo!
    let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
    let keyboardRectangle = keyboardFrame.CGRectValue()
    let keyboardHeight = keyboardRectangle.height

    botMargin.constant = keyboardHeight

func onHideKeyboard() {
    botMargin.constant = 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download