-1

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

wanted

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

unwanted

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.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
DeyaEldeen
  • 10,847
  • 10
  • 42
  • 75
  • I think you are not getting correct IndexPath of particular row that you want on top , so what is the condition when row should be visible on top? – Pandey_Laxman Aug 02 '16 at 10:21
  • 1
    Have you tested to see what happens if you try and scroll to the second or third cell in the table? this might tell you if scrolling the last cell to the top of the view is possible or not. – Wez Aug 02 '16 at 10:22

2 Answers2

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

Imgur

  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
}
Hieu Dinh
  • 692
  • 5
  • 18
1

Have you try this, First declare one CGPoint instance to store current contentOffset of tableview.

var lastScrollPoint = CGPoint()

Now use this code to scroll the tableview

let cell = tableView.cellForRowAtIndexPath(indexPath)
let scrollPoint = CGPointMake(0, cell.frame.origin.y)
self.lastScrollPoint = self.tableView.contentOffset;
self.tableView.setContentOffset(scrollPoint, animated: true)

Now on textFieldShouldReturn set the scroll to default or the lastScroll

func textFieldShouldReturn(textField: UITextField) -> Bool {
    self.tableView.setContentOffset(self.lastScrollPoint, animated: true)
    return true
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183