Skip to content

Instantly share code, notes, and snippets.

@mchirico
Created October 19, 2015 16:06
Show Gist options
  • Save mchirico/eb24615d49c83c319722 to your computer and use it in GitHub Desktop.
Save mchirico/eb24615d49c83c319722 to your computer and use it in GitHub Desktop.
TableViews with animation...trying to come up with something simple here, or easy reference. This needs to be cleaned up.
//
// TableViewController.swift
// TableView
//
// Created by Mike Chirico on 10/18/15.
// Copyright © 2015 Mike Chirico. All rights reserved.
//
// http://www.raywenderlich.com/63089/cookbook-moving-table-view-cells-with-a-long-press-gesture
// Delete:
// http://www.pumpmybicep.com/2014/07/02/uitableview-deleting-moving-and-viewing-rows/
// Understand seque timing
// http://www.freelancemadscience.com/fmslabs_blog/2012/9/24/advanced-storyboard-techniques.html
import UIKit
struct Candy {
let category : String
let name : String
}
var candies = [Candy(category:"Chocolate", name:"chocolate Bar"),
Candy(category:"Chocolate", name:"chocolate Chip"),
Candy(category:"Chocolate", name:"dark chocolate"),
Candy(category:"Hard", name:"lollipop"),
Candy(category:"Hard", name:"candy cane"),
Candy(category:"Hard", name:"jaw breaker"),
Candy(category:"Other", name:"caramel"),
Candy(category:"Other", name:"sour chew"),
Candy(category:"Other", name:"gummi bear")]
class TableViewController: UITableViewController {
let longPress: UILongPressGestureRecognizer = {
let recognizer = UILongPressGestureRecognizer()
return recognizer
}()
override func viewDidLoad() {
super.viewDidLoad()
// Reload the table (Do we need if we also have in viewDidAppear?
// tableView.reloadData()
// Make color black
self.tableView.backgroundColor = UIColor.blackColor()
longPress.addTarget(self, action: "longPressGestureRecognized:")
tableView.addGestureRecognizer(longPress)
}
override func viewDidAppear(animated: Bool) {
// Reload the table
tableView.reloadData()
print("DID reappear")
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return candies.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//ask for a reusable cell from the tableview, the tableview will create a new one if it doesn't have any
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
// Get the corresponding candy from our candies array
let candy = candies[indexPath.row]
// Configure the cell
cell.textLabel!.text = candy.name
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
// Selected color
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.yellowColor()
cell.selectedBackgroundView = bgColorView
return cell
}
func colorForIndex(index: Int) -> UIColor {
let itemCount = candies.count - 1
let val = (CGFloat(index) / CGFloat(itemCount)) * 0.6
return UIColor(red: 1.0, green: val, blue: 0.0, alpha: 1.0)
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = colorForIndex(indexPath.row)
}
override func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
// print("here: \(indexPath)")
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// print("did select: \(indexPath) ")
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
// print("src: \(sourceIndexPath),\(destinationIndexPath)")
}
var sourceIndexPath: NSIndexPath? = nil
var snapshot: UIView? = nil
func longPressGestureRecognized(gesture: UILongPressGestureRecognizer) {
let state: UIGestureRecognizerState = gesture.state;
let location: CGPoint = gesture.locationInView(tableView)
let indexPath: NSIndexPath? = tableView.indexPathForRowAtPoint(location)
if indexPath == nil {
return
}
switch (state) {
case UIGestureRecognizerState.Began:
sourceIndexPath = indexPath;
let cell = tableView.cellForRowAtIndexPath(indexPath!)!
snapshot = customSnapshotFromView(cell)
var center = cell.center
snapshot?.center = center
snapshot?.alpha = 0.0
tableView.addSubview(snapshot!)
UIView.animateWithDuration(0.25, animations: { () -> Void in
center.y = location.y
self.snapshot?.center = center
self.snapshot?.transform = CGAffineTransformMakeScale(1.05, 1.05)
self.snapshot?.alpha = 0.98
cell.alpha = 0.0
})
case UIGestureRecognizerState.Changed:
var center: CGPoint = snapshot!.center
center.y = location.y
snapshot?.center = center
// Is destination valid and is it different from source?
if indexPath != sourceIndexPath {
// ... update data source.
// Here's where you move
print("\(sourceIndexPath!.row),\(indexPath!.row)")
let tmp = candies[sourceIndexPath!.row]
candies[sourceIndexPath!.row] = candies[indexPath!.row]
candies[indexPath!.row] = tmp
// candies.exchangeObjectAtIndex(indexPath!.row, withObjectAtIndex: sourceIndexPath!.row)
// ... move the rows.
tableView.moveRowAtIndexPath(sourceIndexPath!, toIndexPath: indexPath!)
// ... and update source so it is in sync with UI changes.
sourceIndexPath = indexPath;
}
default:
// Clean up.
let cell = tableView.cellForRowAtIndexPath(indexPath!)!
cell.alpha = 0.0
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.snapshot?.center = cell.center
self.snapshot?.transform = CGAffineTransformIdentity
self.snapshot?.alpha = 0.0
// Undo fade out.
cell.alpha = 1.0
}, completion: { (finished) in
self.sourceIndexPath = nil
self.snapshot?.removeFromSuperview()
self.snapshot = nil;
})
break
}
}
// MARK: Helper
func customSnapshotFromView(inputView: UIView) -> UIView {
// Make an image from the input view.
UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0)
inputView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
// Create an image view.
let snapshot = UIImageView(image: image)
snapshot.layer.masksToBounds = false
snapshot.layer.cornerRadius = 0.0
snapshot.layer.shadowOffset = CGSize(width: -5.0, height: 0.0)
snapshot.layer.shadowRadius = 5.0
snapshot.layer.shadowOpacity = 0.4
return snapshot
}
// This is for delete
override func tableView(tableView: UITableView,
commitEditingStyle editingStyle: UITableViewCellEditingStyle,
forRowAtIndexPath indexPath: NSIndexPath) {
print("editingStyle \(editingStyle)")
switch editingStyle {
case .Delete:
// remove the deleted item from the model
candies.removeAtIndex(indexPath.row)
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let r = sender as! UITableViewCell? {
// print("TEXT=\(r.textLabel?.text)")
let vc = segue.destinationViewController as! ViewControllerEdit
if let s = r.textLabel?.text {
vc.labelS = "\(s)"
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment