SwiftUI ForEach index jump by 2 - swift

I am working on SwiftUI ForEach. Below image shows what I want to achieve. For this purpose I need next two elements of array in single iteration, so that I can show two card in single go. I search on a lot but did find any way to jump index swiftUI ForEach.
Need to show two cards in single iteration
Here is my code in which I have added the element same array for both card which needs to be in sequence.
struct ContentView: View {
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 0) {
// I need jump of 2 indexes
ForEach(videos) { video in
//need to show the next two elements of the videos array
HStack {
videoCardView(video: video)
Spacer()
//video + 1
videoCardView(video: video)
}
.padding([.leading, .trailing], 30)
.padding([.top, .bottom], 10)
}
}
}
.background(Color(ColorName.appBlack.rawValue))
}
}
Any better suggestion how to build this view.

While LazyVGrid is probably the best solution for what you want to accomplish, it doesn't actually answer your question.
To "jump" an index is usually referred to as "stepping" in many programming languages, and in Swift it's called "striding".
You can stride (jump) an array by 2 like this:
ForEach(Array(stride(from: 0, to: array.count, by: 2)), id: \.self) { index in
// ...
}
You can learn more by taking a look at the Strideable protocol.

ForEach isn’t a for loop, many make that mistake. You need to supply identifiable data to it which should give you the clue to get your data into a suitable format first. You could process the array into another array containing a struct that has an id and holds the first and second video and pass that to the View that does the ForEach. View structs are lightweight make as many as you need.
You could also make a computed var but that wouldn’t be as efficient as a separate View because you might unnecessary recompute if something different changes.

Foreach is constrained compared to a 'for' loop. One way to fool ForEach into behaving differently is to create a shadow array for ForEach to loop through.
My purpose was slightly different than yours, but the workaround below seems like it could solve your challenge as well.
import SwiftUI
let images = ["house", "gear", "car"]
struct ContentView: View {
var body: some View {
VStack {
let looper = createCounterArray()
ForEach (looper, id:\.self) { no in
Image(systemName: images[no])
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
}
.padding()
}
}
}
//
// return an array of the simulated loop data.
//
func createCounterArray() -> [Int] {
// create the data needed
return Array(arrayLiteral: 0,1,1,2)
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

Related

How to perform `ForEach` on a computed property in SwiftUI

Intro
Imagine we have an infinite range like the range of all possible integers and we can NOT just store them in memory. So we need to calculate them chunk by chunk like:
func numbers(around number: Int, distance: Int) -> [Int] {
((number - distance)...(number + distance))
.map { $0 } // Using `map` ONLY for making the question clear that we do NOT want to use a range
}
so now we can build our view like:
struct ContentView: View {
#State var lastVisibleNumber: Int = 0
var body: some View {
ScrollView(.horizontal) {
LazyHStack {
ForEach(numbers(around: lastVisibleNumber, distance: 10), id:\.self) { number in
Text("\(number)")
.padding()
.foregroundColor(.white)
.background(Circle())
// .onAppear { lastVisibleNumber = number }
}
}
}
}
}
Describing the issue and what tried
In order to load more numbers when needed, I have tried to update the lastVisibleNumber on the appearance of last visible Number by adding the following modifier on the Text:
.onAppear { lastVisibleNumber = number }
Although there is a safe range that is visible and should prevent the infinite loop (theoretically), adding this modifier will freeze the view for calculating all numbers!
So how can we achieve a scroll view with some kind of infinite data source?
Considerations
The range of Int is just a sample and the question can be about an infinite range of anything. (In a form of an Array!)
we don't want unexpected stops (like showing a dummy spinner at the leading or trailing of the list) in the middle of the scrolling.
For this, you should try using table view and data source. Let's assume you have an array of integers. You may create a buffer with an arbitrary number of instances. Let say 100. In that case, with a similar logic, your distance would become a 50. When you scroll, and close enough to the limits, you create another array and reload the table view data source so that you can pretend like you have an infinite array. Be aware that reusable cell and table view implementation is very consistent and optimized.
Don’t refresh view when lastVisibleNumber changes - it just gets into endless loop. You can create Observableobject, store it and update it only on-demand (I provided a button but you can obviously load it onAppear eith some criteria - e.g. last of the array was shown):
class NumberViewModel: ObservableObject {
var lastVisibleNumber = 0
#Published var lastRefreshedNumber = 0
func numbers(distance: Int) -> [Int] {
((lastRefreshedNumber - distance)...(lastRefreshedNumber + distance))
.map { $0 } // Using `map` ONLY for making the question clear that we do NOT want to use a range
}
}
struct ContentView: View {
#StateObject var viewModel = NumberViewModel()
var body: some View {
VStack {
Button("Refresh view", action: {
viewModel.lastRefreshedNumber = viewModel.lastVisibleNumber
})
ScrollView(.horizontal) {
LazyHStack {
ForEach(viewModel.numbers(distance: 10), id:\.self) { number in
Text("\(number)")
.padding()
.foregroundColor(.white)
.background(Circle())
.onAppear { viewModel.lastVisibleNumber = number }
}
}
}
}
}
}

How can I make my View stop unnecessary rendering with using CustomType for Binding in SwiftUI?

I have a CustomType called AppData, and it look like this:
struct AppData {
var stringOfText: String
var colorOfText: Color
}
I am using this AppData in my Views as State or Binding, I have 2 Views in my project called: ContentView and another one called BindingView. In my BindingView I am just using Color information of AppData. And I am expecting that my BindingView render or response for Color information changes! How ever in the fact BindingView render itself even for stringOfText Which is totally unnecessary, because that data is not used in View. I thought that maybe BindingView not just considering for colorOfText but also for all package that cary this data and that is appData So I decided help BindingView to understand when it should render itself, and I made that View Equatable, But that does not helped even. Still BindingView refresh and render itself on changes of stringOfText which it is wasting of rendering. How can I solve this issue of unnecessary rendering while using CustomType as type for my State or Binding.
struct ContentView: View {
#State private var appData: AppData = AppData(stringOfText: "Hello, world!", colorOfText: Color.purple)
var body: some View {
print("rendering ContentView")
return VStack(spacing: 20) {
Spacer()
EquatableView(content: BindingView(appData: $appData))
//BindingView(appData: $appData).equatable()
Spacer()
Button("update stringOfText from ContentView") { appData.stringOfText += " updated"}
Button("update colorOfText from ContentView") { appData.colorOfText = Color.red }
Spacer()
}
}
}
struct BindingView: View, Equatable {
#Binding var appData: AppData
var body: some View {
print("rendering BindingView")
return Text("123")
.bold()
.foregroundColor(appData.colorOfText)
}
static func == (lhs: BindingView, rhs: BindingView) -> Bool {
print("Equatable function used!")
return lhs.appData.colorOfText == rhs.appData.colorOfText
}
}
When using Equatable (and .equatable(), EquatableView()) on Views, SwiftUI makes some decisions about when to apply our own == functions and when it is going to compare the parameters on its own. See another one of my answers with more details about this here: https://stackoverflow.com/a/66617961/560942
In this case, it appears that even if Equatable is declared, SwiftUI skips it because it must be deciding that the POD (plain old data) in the Binding is determined to be non-equal and therefore it's going to refresh the view (again, even though one would think that the == would be enough to force it not to).
In the example you gave, obviously it's trivial for the system to re-render the Text element, so it doesn't really matter if this re-render happened. But, in the even that there actually are consequences to re-rendering, you could encapsulate the non-changing parts into a separate child view:
struct BindingView: View {
#Binding var appData: AppData
var body: some View {
print("rendering BindingView")
return BindingChildView(color: appData.colorOfText)
}
//no point in declaring == since it won't get called (at least with the current parameters
}
struct BindingChildView : View {
var color: Color
var body: some View {
print("rendering BindingChildView")
return Text("123")
.bold()
.foregroundColor(color)
}
}
In the above code, although the BindingView is re-rendered each time (although at basically zero cost, because nothing will change), the new child view is skipped because its parameters are equatable (even without declaring Equatable). So, in a non-contrived example, if the child view were expensive to render, this would solve the issue.

SwiftUI Add to ForEach array without causing the entire view to reload

if I have something like this:
struct ContentView: View {
var results = [Result(score: 8), Result(score: 5), Result(score: 10)]
var body: some View {
VStack {
ForEach(results, id: \.id) { result in
Text("Result: \(result.score)")
}
}
}
}
And then I have a button that appends sometihng to the results array, the entire ForEach loop will reload. This makes sense, but I'm wondering if there is some way to prevent this. The reason I'm asking is because I have a ForEach loop with a few items, each of which plays an animation. If another item is appended to the array, however, the new item appears at the top of the ForEach, but, since the entire view is reload, the other animations playing in the items stop.
Is there any way to prevent this? Like to add an item to a ForEach array, and have it appear, but not reload the entire ForEach loop?
I assume not, but I would wonder how to get around such an issue.
Create separate view for iterating ForEach content, then SwiftUI rendering engine will update container (by adding new item), but not refresh existed rows
ForEach(results, id: \.id) {
ResultCellView(result: $0)
}
and
struct ResultCellView: View {
let result: Result
var body: some View {
Text("Result: \(result.score)")
}
}
Note: I don't see your model, so there might be needed to confirm it to Hashable, Equatable.
In general not providing an id makes it impossible for the ForEach to know what changed (as it has no track of the items) and therefore does not re-render the view.
E.g.
struct ContentView: View {
#State var myData: Array<String> = ["first", "second"]
var body: some View {
VStack() {
ForEach(0..<self.myData.count) { item in
Text(self.myData[item])
}
Button(action: {
self.myData.append("third")
}){
Text("Add third")
}
}
}
}
This throws an console output (that you can ignore) where it tells you about what I just wrote above:
ForEach<Range<Int>, Int, Text> count (3) != its initial count (2).
`ForEach(_:content:)` should only be used for *constant* data.
Instead conform data to `Identifiable` or use `ForEach(_:id:content:)`
and provide an explicit `id`!
For your code try this:
Tested on iOS 13.5.
struct ContentView: View {
#State var results = [Result(score: 8), Result(score: 5), Result(score: 10)]
var body: some View {
VStack {
ForEach(0..<self.results.count) { item in
// please use some index test on production
Text("Result: \(self.results[item].score)")
}
Button(action: {
self.results.append(Result(score: 11))
}) {
Text("Add 11")
}
}
}
}
class Result {
var score: Int
init(score: Int) {
self.score = score
}
}
Please note that this is a "hacky" solution and ForEach was not intended to be used for such cases. (See the console output)

Managing SwiftUI state in a typical list -> details app

I'm building an app that's similar in structure to the Apple tutorial. My app has a ListView, which navigates to a DetailsView. The DetailsView is composed of a UIKit custom UIView, which I wrap with a UIViewRepresentable. So far, so good.
Now I have for now a list (let's say, of addresses) that I instantiate in memory, to be replaced with core data eventually. I'm able to bind (using #EnvironmentObject) the List<Address> to the ListView.
Where I'm stuck is binding the elements for each DetailsView. The Apple tutorial, referenced above, does something which I think isn't great - for some reason (that I can't figure out), it:
Binds the List to the details view (using #EnvironmentObject)
Passes the element (in the Apple tutorial case, landmark, in my case, an address) to the details view
During updating in response to a user gesture, it effectively searches the List for the element, to update the element in the list. This seems expensive especially if the list is large.
Here's the code for #3 which to me is suspect:
Button(action: {
self.userData.landmarks[self.landmarkIndex].isFavorite.toggle()
})
In their code, self.landmarkIndex does a linear search:
var landmarkIndex: Int {
userData.landmarks.firstIndex(where: { $0.id == landmark.id })!
}
What I'm trying to do is to bind the element directly to the DetailsView and have updates to the element update the list. So far, I have been unable to achieve this.
Does anyone know the right way? It seems like the direction the tutorial is pointing to does not scale.
Instead of passing a Landmark object, you can pass a Binding<Landmark>.
LandmarkList.swift: Change the iteration from userData.landmark to their indices so you can get the binding. Then pass the bidding into LandmarkDetail and LandmarkRow
struct LandmarkList: View {
#EnvironmentObject private var userData: UserData
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Show Favorites Only")
}
ForEach(userData.landmarks.indices) { index in
if !self.userData.showFavoritesOnly || self.userData.landmarks[index].isFavorite {
NavigationLink(
destination: LandmarkDetail(landmark: self.$userData.landmarks[index])
.environmentObject(self.userData)
) {
LandmarkRow(landmark: self.$userData.landmarks[index])
}
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
LandmarkDetail.swift: Change landmark into Binding<Landmark> and toggle the favorite based on the binding
#Binding var landmark: Landmark
.
.
.
Button(action: {
self.landmark.isFavorite.toggle()
}) {
if self.landmark
.isFavorite {
Image(systemName: "star.fill")
.foregroundColor(Color.yellow)
} else {
Image(systemName: "star")
.foregroundColor(Color.gray)
}
}
LandmarkRow.swift: Change landmark to a Binding
#Binding var landmark: Landmark
Here is an example of approach to use binding directly to model Address item
Assuming there is view model like, where Address is Identifiable struct
class AddressViewModel: ObservableObject {
#Published var addresses: [Address] = []
}
So somewhere in ListView u can use the following
ForEach (Array(vm.addresses.enumerated()), id: \.element.id) { (i, address) in
NavigationLink("\(address.title)",
destination: DetailsView(address: self.$vm.addresses[i])) // pass binding !!
}

Text not appearing but onAppear triggers

I am trying to use forEach in HStack and VStack. I am using Text in them and Text is not appearing while running but onAppear print values. Please have a look on my code. Why Text is not appearing? How can I make this work?
#State var sd = ["1","2","3","4","5","6","7"]
VStack {
ForEach(0...sd.count/3) { _ in
HStack {
ForEach(0...2) { _ in
if(self.sd.isEmpty) {
} else {
Text("Test")
.onAppear() {
if(!self.sd.isEmpty) {
print("i appeared")
self.sd.removeFirst()
}
}
}
}
Spacer()
}
}
}
What I am trying to achieve here?
I am trying to create a HStacks with maximum 3 Texts in it. I am using array here only to rendered Text 7 times.
Expected result with array with 7 elements--->
Want to create a VStack of 3 HStacks, In first 2 HStacks I want to render Text 3 times and in last HStack I want only one Text. (Like I have 7 array elements that's why 3 texts in first two hstacks and one in last hstack). If array has 10 elements, then 3 Hstacks of 3 Texts and last Stack with 1 Text. I am unable to render Text because my array is #state var and it refresh view.body every time I remove firstElement from it.
Is there any way to achieve this behaviour I am trying to achieve by using SwiftUI only. I don't want to use UICollection view.
You generally don't want to change a #State variable as a side-effect of the evaluation of body; in this case, your self.sd.removeFirst() is causing the body to be marked as needing to be re-evaluated, so SwiftUI just keeps calling it until your sd array is empty, which is why you don't see anything being rendered.
To get the effect you want, this is one way you can do it:
import SwiftUI
struct ContentView : View {
#State private var sd = ["1","2","3","4","5","6","7"]
private let columns = 3
var body: some View {
VStack {
ForEach(Array(stride(from: 0, to: sd.count, by: columns))) { row in
HStack {
ForEach(0..<self.columns) { col in
if row + col < self.sd.count {
Text("\(self.sd[row + col])")
}
}
}
}
}
}
}
P.S. Most attempts to modify state within the body evaluation seem to result in the runtime warning Modifying state during view update, this will cause undefined behavior. – it seems that your array mutation somehow side-stepped this check, but hopefully that sort of thing will be called out at runtime in the future.