Skip to content

Instantly share code, notes, and snippets.

@cmoulton
Last active April 4, 2020 08:48
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cmoulton/324c2ecfe39647fb74d3 to your computer and use it in GitHub Desktop.
Save cmoulton/324c2ecfe39647fb74d3 to your computer and use it in GitHub Desktop.
UITableView updates example. See https://grokswift.com/uitableview-updates/
//
// ViewController.swift
// starWarsTableViewUpdates
//
// Created by Christina Moulton on 2015-10-17.
// Copyright (c) 2015 Teak Mobile Inc. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView?
var movies:Array<String>? = ["Star Wars", "The Empire Strikes Back", "A New Hope"]
var tapCount = 0
override func viewDidLoad() {
super.viewDidLoad()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "buttonTapped:")
self.navigationItem.rightBarButtonItem = addButton
}
func buttonTapped(sender: AnyObject) {
tapCount++
if (tapCount == 1)
{
// Add the prequels if we're not showing them yet
movies?.insert("The Phantom Menace", atIndex: 0)
movies?.insert("The Attack of the Clones", atIndex: 1)
movies?.insert("Revenge of the Sith", atIndex: 2)
// use a single call to update the tableview with 3 indexpaths
self.tableView?.insertRowsAtIndexPaths(
[NSIndexPath(forRow: 0, inSection: 0),
NSIndexPath(forRow: 1, inSection: 0),
NSIndexPath(forRow: 2, inSection: 0)],
withRowAnimation: .Automatic)
}
else if (tapCount == 2)
{
// Add the sequels, even though they don't exist yet
// use one call to delete and one call to add rows to the tableview
// so we need to wrap them in beginUpdates()/endUpdates()
if let count = movies?.count
{
self.tableView?.beginUpdates()
// add sequels
movies?.append("The Force Awakens")
movies?.append("Episode 8")
movies?.append("Episode 9")
self.tableView?.insertRowsAtIndexPaths(
[NSIndexPath(forRow: count - 3, inSection: 0),
NSIndexPath(forRow: count + 1 - 3, inSection: 0),
NSIndexPath(forRow: count + 2 - 3, inSection: 0)],
withRowAnimation: .Automatic)
// remove prequels
movies?.removeAtIndex(0)
movies?.removeAtIndex(0)
movies?.removeAtIndex(0)
self.tableView?.deleteRowsAtIndexPaths(
[NSIndexPath(forRow: 0, inSection: 0),
NSIndexPath(forRow: 1, inSection: 0),
NSIndexPath(forRow: 2, inSection: 0)],
withRowAnimation: .Automatic)
self.tableView?.endUpdates()
}
}
}
// MARK: - TableView
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
if let movieTitle = movies?[indexPath.row]
{
cell.textLabel!.text = movieTitle
}
else
{
cell.textLabel!.text = ""
}
print("row: \(indexPath.row), title: \(cell.textLabel!.text!)")
return cell
}
}
@appsird
Copy link

appsird commented Feb 5, 2017

//
//  ViewController.swift
//  starWarsTableViewUpdates
//
//  Created by Christina Moulton on 2015-10-17.
//  Copyright (c) 2015 Teak Mobile Inc. All rights reserved.
//
//  Adapted for Swift 3 by appsird
//
//   1) use a standard Navigation Controller for your storyboard
//   2) assign this file as custom class to your root view controller
//   3) set prototype Identifier to 'Cell'
//

import UIKit

class ViewController: UITableViewController {

    var movies = ["Star Wars", "The Empire Strikes Back", "A New Hope"]
    var tapCount = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(buttonTapped))
        self.navigationItem.rightBarButtonItem = addButton
    }
    
    func buttonTapped(sender: AnyObject) {
        tapCount += 1
        if (tapCount == 1)
        {
            // Add the prequels if we're not showing them yet
            movies.insert("The Phantom Menace", at: 0)
            movies.insert("The Attack of the Clones", at: 1)
            movies.insert("Revenge of the Sith", at: 2)
            
            // use a single call to update the tableview with 3 indexpaths
            let paths = [IndexPath(row: 0, section: 0), IndexPath(row: 1, section: 0), IndexPath(row: 2, section: 0)]
            self.tableView.insertRows(at: paths, with: .automatic)
        }
        else if (tapCount == 2)
        {
            // Add the sequels, even though they don't exist yet
            // use one call to delete and one call to add rows to the tableview
            // so we need to wrap them in beginUpdates()/endUpdates()
            let count = movies.count
            if count > 0
            {
                self.tableView.beginUpdates()
                
                // add sequels
                movies.append("The Force Awakens")
                movies.append("Episode 8")
                movies.append("Episode 9")
                
                var paths = [IndexPath(row: count - 3, section: 0), IndexPath(row: count + 1 - 3, section: 0), IndexPath(row: count + 2 - 3, section: 0)]
                self.tableView.insertRows(at: paths, with: .automatic)
                
                // remove prequels
                movies.remove(at: 0)
                movies.remove(at: 0)
                movies.remove(at: 0)
                
                paths = [IndexPath(row: 0, section: 0), IndexPath(row: 1, section: 0), IndexPath(row: 2, section: 0)]
                self.tableView.deleteRows(at: paths, with: .automatic)
                self.tableView.endUpdates()
            }
        }
    }
    
    // MARK: - TableView
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("count \(movies.count)")
        return movies.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) as UITableViewCell
        
        let movieTitle = movies[indexPath.row]
        cell.textLabel!.text = movieTitle
        
        print("row: \(indexPath.row), title: \(cell.textLabel!.text!)")
        return cell
    }
    
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment