Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make number of items for iPhone and iPad in LazyVGrid?

Tags:

ios

swift

swiftui

I have LazyVGrid in which i want to make 2 item per row for iPhone and 4 per row in iPad, I am not sure how should i give condition in SwiftUI and how to restrict number of rows

//
//  ContentView.swift
//  DemoProject


import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>
    private var gridItemLayout = [GridItem(.adaptive(minimum: 100))]

    @StateObject private var viewModel = HomeViewModel()

    var body: some View {
        GeometryReader { geometry in
            NavigationView {
                ScrollView {
                    LazyVGrid(columns: gridItemLayout, spacing: 20) {
                        ForEach(viewModel.results, id: \.self) {
                            let viewModel = ResultVM(model: $0)

                            NavigationLink(destination: {
                                DetailView()
                            }, label: {
                                SearchResultRow(resultVM: viewModel)

                            })
                        }
                    }
                }
            }
            .onAppear(perform: {
                viewModel.performSearch()
            })
        }
    }
}

struct SearchResultRow: View {

    let resultVM: ResultVM

    var body: some View {
        HStack {
            RoundedRectangle(cornerRadius: 16).fill(.yellow)
                .frame(maxWidth: .infinity).aspectRatio(1, contentMode: .fit)
                .overlay(Text(resultVM.trackName))
                .onTapGesture {
                }

        }.padding()
            .background(Color.red)
    }
}

enter image description here

like image 768
New iOS Dev Avatar asked Oct 27 '25 08:10

New iOS Dev


1 Answers

Something like this:

LazyVGrid(columns: Array(repeating: .init(.flexible()),
                        count: UIDevice.current.userInterfaceIdiom == .pad ? 4 : 2)) {
        ForEach(categories, id: \.name) { category in
                    
        }
}
like image 176
cora Avatar answered Oct 28 '25 22:10

cora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!