如何使用撤消管理器还原此更改

时间:2019-04-25 18:23:45

标签: ios swift uiimageview uiimage nsundomanager

我的目标是用笔触擦除UIImage,然后撤消更改。我设置了2个UIImage

临时图像-擦除时显示的图像。

主图像-首先隐藏。抬起手指时,主图像将设置为“临时”,以便您可以看到所做的更改。主图像将用于其他目的。

删除工作正常,但是当您点击撤消时,什么也没有发生。当您点按两次时,有时会删除一行。之后的任何轻按似乎都无济于事。如何设置UndoManager删除这些笔画?

如果有帮助,这里是github

var startingPoint: CGPoint!
var touchPoint: CGPoint!
var currentPhoto: UIImage?

...

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    mainImageView.isHidden = true
    tempImageView.isHidden = false
    let touch = touches.first
    startingPoint = touch?.location(in: self.tempImageView)
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    touchPoint = touch?.location(in: self.tempImageView)
    if touchPoint.y <= -0 || touchPoint.y >= (tempImageView.frame.height) {
        return
    }

    UIGraphicsBeginImageContextWithOptions(tempImageView.bounds.size, false, 0)
    tempImageView.image?.draw(in: tempImageView.bounds)

    if let context = UIGraphicsGetCurrentContext() {
        context.setBlendMode(CGBlendMode.clear)
        context.setLineCap(CGLineCap.round)
        context.setLineWidth(15)
        context.beginPath()
        context.setBlendMode(CGBlendMode.clear)
        context.move(to: startingPoint)
        context.addLine(to: touchPoint)
        context.strokePath()

        tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        currentPhoto = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        startingPoint = touchPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    mainImageView.isHidden = false
    tempImageView.isHidden = true

    setNewImage(newImage: currentPhoto)
}

func setNewImage(newImage: UIImage?) {
    undoManager?.registerUndo(withTarget: self, handler: { (targetSelf) in
        self.mainImageView.image = newImage
    })
    mainImageView.image = newImage
}

0 个答案:

没有答案