我正在尝试在SwiftUI中使用PencilKit
。
updateUIView
函数中检测到哪个Binding
变量已更新?例如,更改颜色时,我不想清除画布。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)
}
}
答案 0 :(得分:0)
这可以解决问题:
func updateUIView(_ canvasView: PKCanvasView, context: Context) {
if clear != context.coordinator.pkCanvas.clear{
canvasView.drawing = PKDrawing()
}
canvasView.tool = PKInkingTool(.pen, color: color, width: 10)
}
答案 1 :(得分:0)
我多次观察到类似的模式,在这里,我们在SwiftUI-value-declarative-state-managed
世界和xKit-OOP-imperative-action-managed
世界之间进行了相互交流……并且尝试将所有事物从一个放到另一个,或者反之亦然。
我有一个主意,那就是最好让每个性质都保留,并且在两者之间有一些调解人或演员...所以对于您的用例,我认为我会采取不同的方式,例如(草稿,未经测试,供考虑):
struct ContentView: View {
//@State var color = UIColor.black // < both these have nothing to ContentView
//@State var clear = false
let pkActor = PKCanvasActor() // < mediator, reference type
var body: some View {
VStack{
PKCanvas(actor: pkActor)
VStack(){
Button("Change to BLUE"){ self.pkActor.use(color: UIColor.blue) }
Button("Change to GREEN"){ self.pkActor.use(color: UIColor.green) }
Button("Clear Canvas"){ self.pkActor.clear() }
}
}
}
}
这里某处
func makeUIView(context: Context) -> PKCanvasView {
let canvas = PKCanvasView()
self.actor.canvas = canvas // but think to avoid cycle reference
和纯OOP部分
class PKCanvasActor {
var canvas: PKCanvasView
func use(color: Color) {
// do anything with canvas color
}
func clear() {
canvas.drawing = PKDrawing()
}
// ... any more actions
}
当然,我为SwiftUI Button interact with Map中的类似情况提出了一种简单的方法...但是以上方法对我来说似乎更可取。
备注:可能会说Coordinator是为此目的而设计的,但是它的生命周期是由SwiftUI内部人员管理的,并且它参与了这些内部工作流程,因此我避免介入那些关系...