简体   繁体   中英

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.

  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
}

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
}

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