I have implemented in SwiftUI the following code:
import SwiftUI
struct onAppearmodifier: View {
@State var mytext: String = "Start"
let symbols: [String] = ["globe", "heart.fill","house.fill"]
var body: some View {
NavigationView {
ScrollView {
ForEach(0..<200) { _ in
Rectangle()
.frame(width: 200, height: 200, alignment: .center)
.padding()
.onAppear {
//call the function that I want to build
}
}
}
.onAppear {
mytext = "Fine"
}
}
}
And I want to build a function using stride to show on canvas every each rectangle an SFSymbolthat I have declared above with period three, and I want to call this function inside onAppear() modifier for a specific number of rectangles. My idea is to implement a function of a certain type and to use the following block if I am right
for index in stride(from: 0, to: symbols.count, by: 3) {
let symbolGroup = Group {
Image(systemName: symbols[index])
Image(systemName: symbols[index + 1])
Image(systemName: symbols[index + 2])
But I don’t know how to code it after various tentatives. I am stuck. Any help or other suggestion will be appreciated.
2
Answers
I’m not sure why you’d think
onAppear
is useful here. If you want an image, use anImage
.The "period" can be implemented by taking the remainder of the current index (don’t throw it away with
_
!) of theForEach
divided by 3 (or however many images you have).I’m not sure why you’d use a
Rectangle
either. Perhaps you want to use the image as anoverlay
of rectangles?It sounds like you want to have rows in your scroll view, each row with 3 symbols on. You should build a separate child view that takes an array of the symbols to display on each row. You then also need a function that produces these arrays.
You need to separate drawing the view and preparing the data. It is quite hard to determine what you are trying to achieve but in this code below the sets of three symbols are set up in a display array and this is run onAppear. There is then a view that takes the array and displays the symbols on each loop of the forEach.
The array handling in this example is pretty crude and needs to be done carefully to avoid indexes out of range. Hopefully it provides you with the way to structure this though.