SwiftUI ForEach based on State int

后端 未结 2 488
日久生厌
日久生厌 2020-12-22 02:13

I am storing a Int value as State in my View. When I press a button the Int increase by one. This is working fine when I print my int value.

I have now a ForEach loo

相关标签:
2条回答
  • 2020-12-22 02:34

    It is not due to state, it is because you use ForEach constructor with constant Range, it is documented feature, so not supposed to update, so it is not updated. The simplest solution is as following - to use identifier joined to your state. It just indicates for rendering engine that ForEach is new so refresh (Tested with Xcode 11.2 / iOS 13.2)

    ForEach(0..<self.s_countVenues)
    {_ in
        HStack(spacing: 0)
        {
            //here comes my view
        }
    }.id(s_countVenues)
    
    0 讨论(0)
  • 2020-12-22 02:53

    from apple docs

    extension ForEach where Data == Range<Int>, ID == Int, Content : View {
    
        /// Creates an instance that computes views on demand over a *constant*
        /// range.
        ///
        /// This instance only reads the initial value of `data` and so it does not
        /// need to identify views across updates.
        ///
        /// To compute views on demand over a dynamic range use
        /// `ForEach(_:id:content:)`.
        public init(_ data: Range<Int>, @ViewBuilder content: @escaping (Int) -> Content)
    }
    

    So, you have to use (as suggested by Apple)

    struct ContentView: View {
        @State var counter = 0
        var body: some View {
            VStack {
                ForEach(0 ..< counter, id:\.self) { i in
                        Text("row: \(i.description)")
                    }
                Button(action: {
                    self.counter += 1
                }, label: {
                    Text("counter \(counter.description)")
                })
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题