我正在构建一个AR应用程序。这是我的代码
内容视图:
@State var timeAccumulate = 0
let styleCount = 2
let timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect()
var body: some View {
let vc = ARViewContainer(timeAccumulate: timeAccumulate)
.edgesIgnoringSafeArea(.all)
.onAppear(perform: { getData() })
.onReceive(timer) { _ in
timeAccumulate = (timeAccumulate + 1) % styleCount
}
return vc
}
ARViewContainer:
struct ARViewContainer: UIViewRepresentable {
var timeAccumulate: Int
let boxAnchor = try! Experience.loadBox()
let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
func makeUIView(context: Context) -> ARView {
let arView = ARView(frame: .zero)
arView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
arView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
for i in 1...(imageOrder.count+1-1) {
let entity = boxAnchor.findEntity(named: "box(i)")!
let modelEntity = entity.children[0]
modelEntity.generateCollisionShapes(recursive: true)
arView.installGestures([.all], for: modelEntity as! Entity & HasCollision)
}
arView.scene.anchors.append(boxAnchor)
return arView
}
func updateUIView(_ uiView: ARView, context: Context) {
print(timeAccumulate)
for i in 1...(imageOrder.count+1-1) {
let boxThis = boxAnchor.findEntity(named: "box(i)")!
var modelEntity: ModelEntity!
if timeAccumulate == 0 {
modelEntity = try! ModelEntity.loadModel(named: "Box", in: Bundle.main)
boxThis.children[0] = modelEntity
} else {
modelEntity = try! ModelEntity.loadModel(named: "Chess1", in: Bundle.main)
boxThis.children[0] = modelEntity
}
do {
var material = SimpleMaterial()
let location = documents.appendingPathComponent("(i).jpg")
let tre = try TextureResource.load(contentsOf: location, withName: "(i).jpg")
material.baseColor = try MaterialColorParameter.texture(tre)
material.roughness = .float(0.0)
(modelEntity as Entity & HasModel).model?.materials = [material]
}catch{
//print("no image", count)
}
}
}
}
我想要25个盒子每十秒转换成另一个模型,盒子,然后是象棋,然后是盒子,然后是象棋
我确定参数timeAccumulate是工作的,它是0,然后是1,然后是0,然后是1。
但是视图没有改变。它一直是一个盒子。
我错过了什么?谢谢你。
修复以下错误,它就会成功了:
-
在
ContentView
结构体中使用$
作为timeAccumulate
属性包装器以获得绑定结构体ARViewContainer(timeAccumulate: $timeAccumulate)
-
则
ARViewContainer
结构体中的timeAccumulate
属性使用@Binding
属性@Binding var timeAccumulate: Int
-
baseColor
仍然在iOS 15中工作,但它将与iOS 16无关。因此,使用color
代替:var material = SimpleMaterial() material.color = .init(tint: .white, texture: .init(try! .load(named: "texture.png")))
您正在做的是将timeAccumulate设置为@State的第一个值。试着让你的var timeAccumulate: Int
绑定,这样它就可以监听你的@State变量的变化。
@Binding var timeAccumulate: Int