基于 State int 的 SwiftUI ForEach [英] SwiftUI ForEach based on State int

查看:28
本文介绍了基于 State int 的 SwiftUI ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一个 Int 值作为 State 存储在我的视图中.当我按下按钮时,Int 增加一.当我打印 int 值时,这工作正常.

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.

我现在有一个 ForEach 循环,它基于这个 Int 进行迭代.默认情况下,当我将 State 设置为 2 时,它在开始时工作正常.但是,当我增加 Int 时,不会再次调用我的 ForEach.

I have now a ForEach loop, which iterates based on this Int. When I set my State on 2 by default it works fine at the beginning. However, when I increase that Int my ForEach is not called again.

我知道 State 会重新加载我的实际视图.它是否只加载特定的部分?

I understand that State will reload my actual view. Does it only load specific parts?

在此声明我的状态:

@State var s_countVenues   : Int = 2

这是我使用的 ForEach.它在开始时有效,但是更改 s_countVenues 不会更新视图.

This is the ForEach I use. It works at the beginning, however changing s_countVenues does NOT update the view.

ForEach(0..<self.s_countVenues)
{_ in
    HStack(spacing: 0)
    {
        //here comes my view
    }
}

如有必要,我在这里将我的价值加一.它有效,我打印了更改,如果我在标签中使用它,标签会更新.

If necessary, here I am increasing my value by one. It works, I printed the changes and if I use it inside a Label, the Label gets updated.

self.s_countVenues += 1

TL:DR:

我的 Int 状态正在运行.能增加,在标签里面打印.但是,将其用作 ForEach 中的 Statement 不会在更改后再次调用该循环.

My Int State is working. I can increase and print it inside a label. However, using it as Statement in ForEach does not call that loop again after changing.

推荐答案

来自苹果文档

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)
}

因此,您必须使用(如 Apple 建议的那样)

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)")
            })
        }
    }
}

这篇关于基于 State int 的 SwiftUI ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆