๐Ÿ–ผ๏ธTestItemsView

SwiftUI โŸฉ Layout โŸฉ Grids โŸฉ examples โŸฉ ItemsView โŸฉ TestItemsView

โฌ†๏ธ ้œ€่ฆ๏ผš .dimension(), .shadowedBorder()

import SwiftUI

struct TestItemsView: View {
    
    // โญ๏ธ source of truth
    @State private var size = CGSize(300, 200)
    @State private var idealRatio: CGFloat = 1
    
    let items = Array(1...25)
    
    // computed properties
    var layout: RatioRetainingLayout {
        RatioRetainingLayout(idealRatio, count: items.count, in: size)
    }
    
    var body: some View {
        VStack {
            ScrollView { itemsView }
            display
            controls
        }
        .padding()
    }
}

extension TestItemsView {
    
    /// cell aspect ratio
    var ratio: CGFloat { size.aspectRatio / layout.cols * layout.rows }
    
    /// a view with layed out item views
    var itemsView: some View {
        // ๐Ÿ‘” ItemsView: layout item views
        ItemsView(items: items) { size in               
            RatioRetainingLayout( // โญ inject layout instance
                idealRatio, count: items.count, in: size
            )
        } itemView: { i in        // โญ inject view builder
            Color(hue: 0.8, saturation: 0.6, brightness: 0.5)
                .padding(1)
                .overlay { Text("\(i)").shadow(radius: 2) }
        }
        .frame(size)              // โญ proposed size
        .dimension(.topLeading, arrow: .blue, label: .orange)  // ๐ŸŒ€View+
        .padding(4)
        .shadowedBorder()         // ๐ŸŒ€View+ .shadowedBorder()
        .padding(40)
    }
    
    /// sliders to control proposed size, ideal ratio
    var controls: some View {
        // ๐Ÿ‘” SizeRatioControl
        SizeRatioControl(size: $size, idealRatio: $idealRatio)
    }
    
    var display: some View {
        VStack {
            Text("Cells try to maintain their aspect ratio.")
                .font(.title3)
            Group {
                Text("ideal cell aspect ratio = \(idealRatio.decimalPlaces(2))")
                    .foregroundColor(.secondary)
                VStack {
                    Text("current cell aspect ratio = \(ratio.decimalPlaces(2))")
                    Text("rows: \(layout.rows), cols: \(layout.cols)")
                }
                .padding(4)
                .border(.red)
            }
            .font(.caption)
        }
    }
}

// ----------------
//     Previews
// ----------------

struct TestItemsView_Previews: PreviewProvider {
    static var previews: some View {
        TestItemsView()
            .overlay {
                Text("Preview")
                    .font(.largeTitle)
                    .bold()
                    .foregroundColor(.orange)
                    .opacity(0.3)
                    .shadow(radius: 2)
            }
    }
}

Last updated