如何在 Mac OS X 和 Swift 4 上使用 NSUndoManager 为 NSBezierPath 添加撤消?

How to add Undo for NSBezierPath with NSUndoManager on Mac OS X with Swift 4?

我正在尝试为 NSBezierPath 添加撤消功能。

此函数使用 NSBezierPath 绘制圆,半径为 45。以 mouseLocation 为圆心

然后在 CAShapeLayer 上绘制 NSBezierPath 并添加到 NSViewController 的视图中。

我应该如何为该方法添加撤消功能。 提前谢谢你。

func bezierPathMouseUndoTest(mouseLocation: CGPoint, color: NSColor) {

    let frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(100), height: CGFloat(100))

    // The path should be the entire circle.
    let circlePath = NSBezierPath.init()
    circlePath.appendArc(withCenter: CGPoint(x: mouseLocation.x, y: mouseLocation.y), radius: (frame.size.width - 10)/2, startAngle: CGFloat(90.0), endAngle: CGFloat(-270.0), clockwise: true) // start from up

    // Setup the CAShapeLayer with the path, colors, and line width
    circleLayer = CAShapeLayer()

    circleLayer.path = circlePath.CGPath

    circleLayer.fillColor = NSColor.clear.cgColor
    circleLayer.strokeColor = color.cgColor
    circleLayer.lineWidth = 5.0;

    circleLayer.strokeEnd = 1.0
    circleLayer.frame = frame

    // Add the circleLayer to the view's layer's sublayers
    self.view.layer?.addSublayer(circleLayer)
    self.undoManager?.setActionName("Draw Bezier Path")

}

谢谢 Willeke。

我使用另外两个函数添加了将 bezierPath 添加到新图层的撤消操作。并对上面的代码做了一点改动。

将"self.view.layer?.addSublayer(circleLayer)"替换为 "self.addSublayer(layer: circleLayer)"

删除"self.undoManager?.setActionName("绘制贝塞尔曲线路径")"

在下面添加两个函数

func addSublayer(layer: CALayer) {
    undoManager?.registerUndo(withTarget: self, selector: #selector(removeSublayer), object: layer)
    self.undoManager?.setActionName("Draw Bezier Path")
    self.view.layer?.addSublayer(layer)

}

func removeSublayer(layer: CALayer) {
    undoManager?.registerUndo(withTarget: self, selector: #selector(addSublayer), object: layer)
    layer.removeFromSuperlayer()
}