Reputation: 615
I'm using Apple's VisionKit and storing the images in both an Image
and Data
array, like so:
@State private var image: [Image] = []
@State var imageData : Data = .init(count: 0)
And appending the data like this:
for imageIndex in imagePerPage! {
var uiImage = UIImage(cgImage: imageIndex)
let converted = Image(uiImage: uiImage)
image.append(converted)
imageData.append(uiImage.jpegData(compressionQuality: 0.00005)!)
}
I'm passing the data to another view which is fine, as I can use print(image.count)
and I get the expected count. However, I'm having issues with iterating over my array and display the images. I use a ForEach
statement and I get an error nagging me that the data type Image
must conform to Hashable
(I'm not using a model/struct)
@State var image: [Image]
ForEach(image.count, id: \.self) { image in
Image(image)
.resizable()
.frame(width: getScreen().width, height: getScreen().height * 0.85)
.aspectRatio(contentMode: .fit)
}
I've even tried a for loop i.e. for x in images {///}
.
Is there anyway in which I can resolve this issue?
Would be much appreciated!
Upvotes: 0
Views: 6734
Reputation: 52367
You can use ForEach
with a range: 0...10
.
Secondly, your image
array already holds Image
s, so you shouldn't need to call Image
again.
ForEach(0..<image.count) { imageIdx in
image[imageIdx]
.resizable()
.frame(width: getScreen().width, height: getScreen().height * 0.85)
.aspectRatio(contentMode: .fit)
}
Now, that being said, I'm a little skeptical of the idea of keeping the Image
views in the array. I think you'd be better off making your array full of UIImage
objects and then calling them inside the view with Image(uiImage:)
inside your view.
Might look more like this:
@State var images: [UIImage]
var body: some View {
ForEach(0..<images.count) { imageIdx in
Image(uiImage: images[imageIdx])
.resizable()
.frame(width: getScreen().width, height: getScreen().height * 0.85)
.aspectRatio(contentMode: .fit)
}
}
Finally, using ForEach
with indexes instead of IDs could lead to funny issues later if your array gets updated with images as SwiftUI may not know to refresh the view. At that point, it would be better to use a struct wrapper for the images and give them real IDs.
Upvotes: 4