简体   繁体   English

修改 SwiftUI 中 ForEach 内的视图

[英]Modify view inside a ForEach in SwiftUI

I tried to update the position of one item of a ForEach.我尝试更新 ForEach 的一项的 position。 I want to drag only one item out of the array in the ForEach.我只想从 ForEach 的数组中拖出一个项目。 The rest should stay the same. rest 应该保持不变。 I tried several different ways and the outcome was always that all items where dragged or no item at all.我尝试了几种不同的方法,结果总是所有项目都被拖动或根本没有项目。

I am really frustrated at this stage, so I would be more than happy, if you can help me, If you need further information feel free to ask.在这个阶段我真的很沮丧,所以我会非常高兴,如果你能帮助我,如果你需要更多信息,请随时询问。 I am new here on stackOverflow.我是 stackOverflow 的新手。

struct ContentView: View {

    var texts: [String] = ["Test1", "Test2"]

    @State var positon: CGSize = .zero

    var body: some View {
        HStack {
            ForEach(texts, id: \.self) { text in
                Text(text)
                    .offset(y: positon.height)
                    .gesture(
                        DragGesture()
                            .onChanged { value in
                                positon = value.translation
                            }
                            .onEnded { value in
                                positon = .zero
                            }
                    )
            }
        }
    }
}

Both Text views are dragged at the same time, because both Text views offset(y: ...) depend on the same position variable.两个Text视图同时被拖动,因为两个Text视图offset(y: ...)依赖于同一个position变量。


Something like this should work:像这样的东西应该工作:

struct ContentView: View {

    var texts: [String] = ["Test1", "Test2"]

    var body: some View {
        HStack {
            ForEach(texts, id: \.self) { text in
                DraggableText(text: text)
            }
        }
    }
}

struct DraggableText: View {

    var text: String

    @GestureState var position: CGSize = .zero

    var body: some View {
        Text(text)
            .offset(y: position.height)
            .gesture(
                DragGesture().updating($position, body: { value, state, transaction in
                    state = value.translation
                })
            )
    }
}

Each DraggableText has its own position property.每个DraggableText都有自己的 position 属性。

You are changing the value position which is used the same way for both views.您正在更改值position ,这两个视图的使用方式相同。

You will need a separate @State variable for each view if you want them to move independently, or some other way to keep track of their positions separately.如果您希望它们独立移动,或者以其他方式分别跟踪它们的位置,则每个视图都需要一个单独的 @State 变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM