2016-08-11 3 views
4

Ich habe eine UITableView und ich versuche, 36 Zeilen hinein zu laden und blättern Sie dann die letzte Zelle hinunter.Scrollen Sie den ganzen Weg bis zum Ende von UITableView

Ich habe dies versucht:

func reloadData(){ 
    chatroomTableView.reloadData() 
    chatroomTableView.scrollToBottom(true) 
} 


extension UITableView { 
    func scrollToBottom(animated: Bool = true) { 
     let sections = self.numberOfSections 
     let rows = self.numberOfRowsInSection(sections - 1) 
     if (rows > 0){ 
      self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true) 
     } 
    } 
} 

Aber es scrollt nur halb nach unten.

+0

Haben 'rows' und' sections' den erwarteten Wert in Ihrer Funktion 'scrollToBottom', wenn ' S heißt? – rmaddy

+0

Ja, rows = 36 und sections = 1. Es scrollt jedoch nur in Zeile 10 von Abschnitt 0. –

+0

Versuchen Sie, Ihren Aufruf von 'scrollToBottom' innerhalb eines' dispatch_async' oder vielleicht 'dispatch_after' einzubinden. – rmaddy

Antwort

7

Wenn Ihre Anforderung ist für das letzte cell von tableView Sie setContentOffset so bewegen können, so dass Sie auf die letzte Zelle des tableView bewegen kann.

let scrollPoint = CGPoint(x: 0, y: self.tableView.contentSize.height - self.tableView.frame.size.height) 
self.tableView.setContentOffset(scrollPoint, animated: true) 



Es war eine Kombination von Antworten. Ich landete dies zu tun:

diese in der reload() Funktion:

func reloadData(){ 
    chatroomTableView.reloadData() 
    dispatch_async(dispatch_get_main_queue(), {() -> Void in 
     let scrollPoint = CGPoint(x: 0, y: self.chatroomTableView.contentSize.height - self.chatroomTableView.frame.size.height) 
     self.chatroomTableView.setContentOffset(scrollPoint, animated: true) 
    }) 
} 

hinzugefügt dies meine UITableViewDelegate:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
     let lastRowIndex = tableView.numberOfRowsInSection(0) 
     if indexPath.row == lastRowIndex - 1 { 
      tableView.scrollToBottom(true) 
     } 
    } 

habe dieses Bild auf die Unterseite meiner .swift Datei :

extension UITableView { 
    func scrollToBottom(animated: Bool = true) { 
     let sections = self.numberOfSections 
     let rows = self.numberOfRowsInSection(sections - 1) 
     if (rows > 0){ 
      self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true) 
     } 
    } 
} 
Verwandte Themen