gpt4 book ai didi

ios - SwiftUI 中的 PencilKit

转载 作者:行者123 更新时间:2023-11-28 23:22:39 28 4
gpt4 key购买 nike

我正在尝试在 SwiftUI 中使用 PencilKit

  1. 如何在 updateUIView 函数中检测更新了哪个 Binding 变量?例如,我不想在更改颜色时清除 Canvas 。
  2. 有没有比切换 bool 值更好的方法来清除 Canvas ?切换 bool 值会强制执行 updateUIView 函数。
import SwiftUI
import UIKit
import PencilKit

struct ContentView: View {
@State var color = UIColor.black
@State var clear = false

var body: some View {
VStack{
PKCanvas(color: $color, clear:$clear)
VStack(){
Button("Change to BLUE"){ self.color = UIColor.blue }
Button("Change to GREEN"){ self.color = UIColor.green }
Button("Clear Canvas"){ self.clear.toggle() }
}
}
}
}

struct PKCanvas: UIViewRepresentable {
class Coordinator: NSObject, PKCanvasViewDelegate {
var pkCanvas: PKCanvas

init(_ pkCanvas: PKCanvas) {
self.pkCanvas = pkCanvas
}
}

@Binding var color:UIColor
@Binding var clear:Bool

func makeCoordinator() -> Coordinator {
Coordinator(self)
}

func makeUIView(context: Context) -> PKCanvasView {
let canvas = PKCanvasView()
canvas.tool = PKInkingTool(.pen, color: color, width: 10)

canvas.delegate = context.coordinator
return canvas
}

func updateUIView(_ canvasView: PKCanvasView, context: Context) {
// clears the canvas
canvasView.drawing = PKDrawing()

// sets a new color
canvasView.tool = PKInkingTool(.pen, color: color, width: 10)
}
}

最佳答案

这样就可以了:

    func updateUIView(_ canvasView: PKCanvasView, context: Context) {
if clear != context.coordinator.pkCanvas.clear{
canvasView.drawing = PKDrawing()
}
canvasView.tool = PKInkingTool(.pen, color: color, width: 10)
}

关于ios - SwiftUI 中的 PencilKit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59430099/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com