Reputation:
This is my Array of some Rec I need to know if I can read size of this Rec without using GeometryReader, for example width of Rec?
var body: some View {
let arrayOfRec = [Rectangle().frame(width: 100, height: 100), Rectangle().frame(width: 200, height: 200)]
VStack
{
ForEach(0..<arrayOfRec.count) { index in
arrayOfRec[index]
}
}
}
Upvotes: 1
Views: 191
Reputation: 76
Unfortunately, it does not seem possible to get the width and height of the Rectangle without geometry reader in pure SwiftUI. I tried the methods that were attached to that Shape, but nothing resulted in the size.
Unknown what the use case is, but it is possible to make a custom object that holds the width and height of the rectangle.
struct Rectangle_TEST {
var rectangle: Rectangle
var width: CGFloat
var height: CGFloat
init(width: CGFloat, height: CGFloat) {
self.width = width
self.height = height
self.rectangle = Rectangle()
}
func getView(color: Color) -> some View {
return self.rectangle
.fill(color)
.frame(width: self.width, height: self.height)
}
}
struct ContentView: View {
var body: some View {
let arrayOfRec: [Rectangle_TEST] = [Rectangle_TEST(width: 100, height: 100), Rectangle_TEST(width: 200, height: 200)]
VStack {
ForEach(0..<arrayOfRec.count) { index in
Text("Width: \(arrayOfRec[index].width), Height: \(arrayOfRec[index].height)")
arrayOfRec[index].getView(color: .red)
}
}
}
}
Above I made the custom object and stores the width and height that can be accessed individually, and then a function that will return a view, and you can pass in whatever modifiers are needed. But, currently, I don't think it is possible to get the dimensions without geometry reader in SwiftUI.
Upvotes: 1