Using Swift 3.02 (Xcode 8.2) I refer to an undo-solution described in answer: https://stackoverflow.com/a/31450475/7448394.
In the code below I use this solution to test both undo and redo of a drawing. When I press the button for randomDrawing it draws a red line from zero to a random point. When I press the undo-button this line or the last line disappear. But when I press the redo-button nothing happens to the imageView. Obviously the undo is working, I also checked undoManager?.canRedo which changes to true after the undo-action, but why does this redo-action shows no result?
import UIKit
class ViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func undoDrawing(_ sender: AnyObject) {
undoManager?.undo()
}
@IBAction func redoDrawing(_ sender: AnyObject) {
undoManager?.redo()
}
@IBAction func randomDrawing(_ sender: AnyObject) {
let undo: UIImageView = undoManager?.prepare(withInvocationTarget: imageView) as! UIImageView
UIGraphicsBeginImageContext(self.imageView.frame.size)
self.imageView.image?.draw(in: CGRect(x: 0, y: 0, width: self.imageView.frame.size.width, height: self.imageView.frame.size.height))
UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: 0, y: 0))
UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: Int(arc4random_uniform(100) + 100), y: Int(arc4random_uniform(100) + 100)))
UIGraphicsGetCurrentContext()?.setLineWidth(10.0)
UIGraphicsGetCurrentContext()?.setStrokeColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
UIGraphicsGetCurrentContext()?.strokePath()
undo.image = imageView.image
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}