Search code examples
iosswiftundo-redo

Undo redo Operation


I have used the following code for undo redo operation. I am changing the label's background color and my undo/redo operation is working fine but now i have added label's text color so whenever i change only background color or text color individually it works fine but if i change background color and text color both at a time then it will not work properly. what should i do? please help.!

@IBOutlet var myObject: UILabel!

//  MARK: - View Life Cycle
override func viewDidLoad() {
    super.viewDidLoad()
    myObject.backgroundColor = UIColor.yellow
}

func setMyObjectColor(_ color: UIColor) {
        (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectColor(myObject.backgroundColor!)
        myObject.backgroundColor = color
}

func setMyObjectTextColor(_ color: UIColor) {
        (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectTextColor(myObject.textColor!)
        myObject.textColor = color
}

@IBAction func changeColor(_ sender: Any){
    setMyObjectColor(UIColor.blue)
}

@IBAction func changeTextColor(_ sender: Any){
    setMyObjectTextColor(UIColor.white)
}

@IBAction func undo(_ sender: Any) {
    undoManager?.undo()
}

@IBAction func redo(_ sender: Any) {
    undoManager?.redo()
}}

Solution

  • @IBOutlet var myObject: UILabel!
    
    //  MARK: - View Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        myObject.backgroundColor = UIColor.yellow
    }
    
    func setMyObjectColor(_ Backcolor: UIColor) {
            (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectColor(myObject.backgroundColor!)
            myObject.backgroundColor = Backcolor
    }
    
    func setMyObjectTextColor(_ Textcolor: UIColor) {
            (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectTextColor(myObject.textColor!)
            myObject.textColor = Textcolor
    }
    
    func setMyObjectText(_ Text: String) {
        (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectText((myObject.text! as AnyObject) as! String)
        myObject.text = Text
    }
    
    @IBAction func changeColor(_ sender: Any){
        setMyObjectColor(UIColor.blue)
    }
    
    @IBAction func changeTextColor(_ sender: Any){
        setMyObjectTextColor(UIColor.white)
    }
    
    @IBAction func changeText(_ sender: Any) {
        setMyObjectText("Khush")
    }
    
    @IBAction func undo(_ sender: Any) {
        undoManager?.undo()
    }
    
    @IBAction func redo(_ sender: Any) {
        undoManager?.redo()
    }
    

    Using this code my issue is solved.