为用户创建矩阵视图以通过 TextField (SwiftUI) 输入数字 [英] Creating a Matrix View for Users to input numbers via TextField (SwiftUI)

查看:53
本文介绍了为用户创建矩阵视图以通过 TextField (SwiftUI) 输入数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个矩阵,用户可以在其中输入数字并进行计算.目前,我有这样的事情:

I want to construct a matrix where users can input numbers and do calculations. Currently, I have something like this:

@State var dimension = 2
@State var matrixVals = [Double]()

ForEach(0..<dimension, id:\.self) { index in
                    
                    HStack {
                        
                        ForEach(0..<dimension, id:\.self) {i2 in
                            
                            TextField("", text: Binding(
                                get: { if matrixVals.count > index*i2 { return String(matrixVals[index*i2]) } else { return "" }},
                                set: { (newValue) in return self.matrixVals.append(Double(newValue) ?? 1.0) }
                            ))
                            
                            .background(Color.gray)
                            .frame(width: 35 - CGFloat(dimension*3), height: 55 - CGFloat(dimension*3), alignment: .center)
                            .padding(.horizontal, 12 - CGFloat(dimension))
                            .padding(.vertical, 0 - CGFloat(dimension/2))
                            
                        }
                    }
                    
                }

尺寸可以通过按下按钮来增加/减少,所以它应该是动态的.这是我在第一个块上输入 7 后得到的(它将它复制到第一列和行中的每个块).知道我哪里出错了(我认为这很可能与我滥用 index 和 i2 作为索引有关)?

Dimension can be increased/decreased by pressing a button, so it should be dynamic. This is what I get after inputting 7 on the first block (it copies it to every block in the first column and the row). Any idea where I went wrong (I think it's most likely related to my misuse of index and i2 as indices)?

感谢任何建议!

推荐答案

零乘以任意数仍为零.您的错误在这里:

Zero multiplied by any number is still zero. Your bug is here:

index*i2

相反,试试这个:

index*dimension + i2

此外,您可以考虑二维数组(又名数组数组).这可能会让事情变得更容易.

Also, you can consider 2 dimensional array (a.k.a. Array of arrays). This may make things easier.

这篇关于为用户创建矩阵视图以通过 TextField (SwiftUI) 输入数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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