点击任意位置可在画布上添加多个项目


import SwiftUI
struct Level1: View {
@State var tapScore = 0
@State var showingMinedHammer = false
@State var points:[CGPoint] = [CGPoint(x:0,y:0), CGPoint(x:50,y:50)]
@State private var location = CGPoint.zero      // < here !!


func mine() {
tapScore += 1
showMinedHammer()
}

func showMinedHammer() {
self.showingMinedHammer = true
DispatchQueue.main.asyncAfter(deadline: .now() + 99) {
self.showingMinedHammer = false
}
}

var body: some View {
GeometryReader { geometryProxy in
ZStack {
Image("hammer.fill").resizable().frame(width: UIScreen.main.bounds.height * 1.4, height: UIScreen.main.bounds.height)
.gesture(DragGesture(minimumDistance: 0).onEnded { value in
self.location = value.location // < here !!
self.mine()
})
if self.showingMinedHammer {
Image(systemName: "hammer.fill")
.resizable()
.frame(width: 30, height: 30)
.position(self.location)    // < here !!
}
}
}.edgesIgnoringSafeArea(.all)
}

}
struct Level1_Previews: PreviewProvider {
static var previews: some View {
Level1()
}
}
struct GetTapLocation:UIViewRepresentable {
var tappedCallback: ((CGPoint) -> Void)

func makeUIView(context: UIViewRepresentableContext<GetTapLocation>) -> UIView {
let v = UIView(frame: .zero)
let gesture = UITapGestureRecognizer(target: context.coordinator,
action: #selector(Coordinator.tapped))
v.addGestureRecognizer(gesture)
return v
}

class Coordinator: NSObject {
var tappedCallback: ((CGPoint) -> Void)
init(tappedCallback: @escaping ((CGPoint) -> Void)) {
self.tappedCallback = tappedCallback
}
@objc func tapped(gesture:UITapGestureRecognizer) {
let point = gesture.location(in: gesture.view)
self.tappedCallback(point)
}
}

func makeCoordinator() -> GetTapLocation.Coordinator {
return Coordinator(tappedCallback:self.tappedCallback)
}

func updateUIView(_ uiView: UIView,
context: UIViewRepresentableContext<GetTapLocation>) {
}

}

作为SwiftUI的新手,我正在尝试组合手势,让我可以点击屏幕上的任何地方,以添加无限量的";图像";,但是当前图像仅在屏幕上停留很短时间。我哪里错了?我是否应该组合另一个手势,使项目在添加时保持在屏幕上?

您只有一个单数location,因此在您的示例中只会出现一个项。要拥有多个项目,您需要某种集合,如数组。

以下是使用数组的精简示例:

struct Hammer: Identifiable {
var id = UUID()
var location: CGPoint
}
struct Level1: View {
@State var hammers: [Hammer] = [] //<-- Start with `none`

var body: some View {
ZStack {
ForEach(hammers) { hammer in // Display all of the hammers
Image(systemName: "hammer.fill")
.resizable()
.frame(width: 30, height: 30)
.position(hammer.location)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 0).onEnded { value in
self.hammers.append(Hammer(location: value.location)) // Add a Hammer
})
.edgesIgnoringSafeArea(.all)
}
}

注意:我不清楚GeometryReader在你的代码中是什么用的——你声明它,然后使用UIScreen尺寸——通常在SwiftUI中,我们只使用GeometryReader

最新更新