SwiftUI界面赏鉴demo之《寒食帖》Grid布局

SwiftUI 和 Flutter时代编程将成为一个有品位的工作,为此特开辟新板块,用于显示SwiftUI制作的界面demo,供大家赏鉴。

功能

  • List
  • Grid自动布局
  • 分割数组
  • 自定义Cell

效果

SwiftUI界面赏鉴demo之《寒食帖》Grid布局_第1张图片
单数效果
SwiftUI界面赏鉴demo之《寒食帖》Grid布局_第2张图片
偶数效果

代码

import SwiftUI

struct ContentView : View {
    
    let dishes = Dish.all()
    
    var body: some View {
        
        let chunkedDishes = dishes.chunked(into: 3)
        
        return List {
            
            // rows
            ForEach(0..

如何分割数组呢

import Foundation
import SwiftUI

struct Dish: Identifiable {
    
    let id = UUID()
    let name: String
    let price: Double
    let imageURL: String
    
}

extension Dish {
    
    static func all() -> [Dish] {
        
        return [
            Dish(name: "han-shi-tie01-640x350", price: 35, imageURL: "han-shi-tie01-640x350"),
            Dish(name: "han-shi-tie02-640x350s", price: 12, imageURL: "han-shi-tie02-640x350"),
            Dish(name: "han-shi-tie03-640x350", price: 12, imageURL: "han-shi-tie03-640x350"),
            Dish(name: "han-shi-tie04-640x350", price: 15, imageURL: "han-shi-tie04-640x350"),
            Dish(name: "han-shi-tie05-640x350", price: 8, imageURL: "han-shi-tie05-640x350"),
            Dish(name: "han-shi-tie06-640x350", price: 10, imageURL: "han-shi-tie06-640x350"),
            Dish(name: "han-shi-tie07-640x350", price: 12, imageURL: "han-shi-tie07-640x350")
         //    Dish(name: "han-shi-tie07-640x350", price: 12, imageURL: "han-shi-tie07-640x350")
            
        ]
        
    }
    
}
import Foundation


extension Array {
    func chunked(into size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
    }
}

参考资料

https://www.hackingwithswift.com/example-code/language/how-to-split-an-array-into-chunks

更多SwiftUI教程和代码关注专栏

  • 请关注我的专栏icloudend, SwiftUI教程与源码
    https://www.jianshu.com/c/7b3e3b671970

你可能感兴趣的:(SwiftUI界面赏鉴demo之《寒食帖》Grid布局)