I would like to load more data and create additional cells when the user scrolls to the bottom of the table. I'm using JSON data and MySql.
func dataJsonFromURL(url:String)->NSArray { if let data = NSData(contentsOfURL: NSURL(string: url)!) { return ((try! NSJSONSerialization.JSONObjectWithData(data, options: [])) as! NSArray) } else{ return data } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("NCell", forIndexPath: indexPath) as! TableViewCell22 cell.backgroundColor = UIColor .clearColor() let mindata = (data[indexPath.row] as! NSDictionary) }
First off, the tableView(_:cellForRowAt:) method should be as fast as possible. This method is called every time a cell needs to be displayed. The faster it executes, the smoother scrolling the table view will be.
UITableView scrolls back because it's content size is equal to it's frame (or near to it). If you want to scroll it without returning you need add more cells: table view content size will be large then it's frame.
To scroll to the top of our tableview we need to create a new IndexPath . This index path has two arguments, row and section . All we want to do is scroll to the top of the table view, therefore we pass 0 for the row argument and 0 for the section argument. UITableView has the scrollToRow method built in.
There are two main base ways to populate a tableview. The more popular is through Interface Building, using a prototype cell UI object. The other is strictly through code when you don't need a prototype cell from Interface Builder.
you have to use this method
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let lastElement = dataSource.count - 1 if indexPath.row == lastElement { // handle your logic here to get more items, add it to dataSource and reload tableview } }
Xcode 8, Swift 3
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let lastElement = dataSource.count - 1 if !loadingData && indexPath.row == lastElement { indicator.startAnimating() loadingData = true loadMoreData() } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With