简体   繁体   English

在 swift 的闭包内使用变量

[英]Using a variable inside a closure in swift

Here is my ContentView code:这是我的 ContentView 代码:

import SwiftUI

struct GridStack<Content: View>: View {
    let rows: Int
    let columns: Int
    let content: (Character) -> Content

    var body: some View {
        VStack {
            ForEach(1 ..< rows, id: \.self) { row in
                HStack {
                    ForEach(1 ..< self.columns, id: \.self) { column in
                        self.content("C").padding().border(Color.black)
                    }
                }
            }
        }
    }

    init(rows: Int, columns: Int, @ViewBuilder content: @escaping (Character) -> Content) {
        self.rows = rows
        self.columns = columns
        self.content = content
    }
}

And here is the snippet from SceneDelegate.swift这是来自 SceneDelegate.swift 的片段

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    let theSheet = ["A", "M", "A", "N"]
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        let contentView = GridStack(rows: Int(11), columns: Int(11),  content: { _ in Text("\theSheet[3]")})
            
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

In particular please look at the line:特别是请看以下行:

let contentView = GridStack(rows: Int(11), columns: Int(11),  content: { _ in Text(theSheet[3])})

You can see that I have hard coded the value 3 for the index of array theSheet.您可以看到我已经为数组 theSheet 的索引硬编码了值 3。 What I want to do is to dynamically calculate the index using the current "rows" and "columns" value in the formula rows + columns.我想要做的是使用公式行+列中的当前“行”和“列”值动态计算索引。

I request the experts here to help with this.我请求这里的专家帮助解决这个问题。 I am online to provide any further details you need.我在线提供您需要的任何进一步的详细信息。

If I understood your issue correctly, I guess you want to display a character from array in 10*10 grid.如果我正确理解了您的问题,我猜您想在 10*10 网格中显示数组中的字符。 Create a ContentView and call GridStack from ContentView :创建一个ContentView并从ContentView调用GridStack

struct ContentView: View {
    let theSheet = [YOUR_ARRAY]
    var body: some View {
       GridStack(rows: Int(10), columns: Int(10),  content: { index in
        Text(self.theSheet[index]).padding(8).border(Color.black).frame(width: 30)
       })
    }
}

In GridStack return the index,GridStack返回索引,

  1. Replace let content: (Character) -> Content with let content: (Int) -> Content替换let content: (Character) -> Contentlet content: (Int) -> Content
  2. Replace self.content("C").padding().border(Color.black) with self.content((row*self.columns)+column)self.content("C").padding().border(Color.black)替换为self.content((row*self.columns)+column)
  3. Call this ContentView in SceneDelegate like let contentView = ContentView()SceneDelegate中调用这个ContentView就像let contentView = ContentView()
  4. Return Int instead of Character in your GridStackGridStack中返回Int而不是Character

Calculated Index using (row*self.columns)+column使用(row*self.columns)+column计算的索引

Result: https://i.stack.imgur.com/Qdcjg.png结果: https://i.stack.imgur.com/Qdcjg.png

I think that this isn't a good solution to use closures.我认为这不是使用闭包的好解决方案。 SwiftUI means using @State / @ObservableObject / @Environment to change the content. SwiftUI 表示使用@State / @ObservableObject / @Environment 来改变内容。 This is a reactive programming.这是一种反应式编程。

For instance,例如,

struct GridStack<Content: View>: View {
    let rows: Int
    let columns: Int
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        let state = viewModel.state
        return VStack {
            ForEach(1 ..< rows, id: \.self) { row in
                HStack {
                    ForEach(1 ..< self.columns, id: \.self) { column in
                        Text("state: \($0)")
                    }
                }
            }
        }
    }

    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
    }
}

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

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