其他分享
首页 > 其他分享> > SwiftUI实现网格视图(GridView)

SwiftUI实现网格视图(GridView)

作者:互联网

目录

SwiftUI实现网格视图(GridView)

使用两种方法来实现网格视图,一种是利用HStack和VStack组合来实现,另一种利用格子位置来实现。

HStack和VStack组合

使用这种方法的步骤:

  1. 首先实现行视图也就是RowView
  2. 利用RowView实现网格视图,也就是GridView

1. 准备工作

为了方便测试,我们使用颜色来表示每一个格子,因为Color也是View的一种,所以我们对Color做一个扩展,以返回随机颜色

extension Color {
    static var random: Color {
        return Color(red: .random(in: 0...1),
                     green: .random(in: 0...1),
                     blue: .random(in: 0...1))
    }
}

2. 实现RowView

RowView我们可以想到它应该具有的属性:每行的格子个数、要放置的格子数组、格子的宽度

struct RowView: View {
    var itemPerRow: Int
    var views: [AnyView] = []
    var itemWidth: CGFloat {
        UIScreen.main.bounds.width / CGFloat(itemPerRow)
    }
    var body: some View {
        HStack(spacing: 0) {
            ForEach(0..<views.count) { index in
                views[index]
                    .frame(width: itemWidth, height: itemWidth)
            }
        }
    }
}

3. 组合成网格

对于一个网格,我们知道的初始数据应该是:要放置的整个格子数组,每行要放置的个数。行数是不知道的,因此我们需要进行计算。同时为了得到每一行的RowView,我们还需要将整个格子数组划分成一行一行的子数组。

首先计算行数:

    func rowCount(contentNums: Int, itemPerRow: Int) -> Int {
    	//如果能整除那就刚好是这么多行
        if contentNums % itemPerRow == 0 {
            return contentNums / itemPerRow
        }
        //否则还得多出来一行
        return contentNums / itemPerRow + 1
    }

根据内容数组计算每一行的子数组

struct GridContentView: View {
    var itemPerRow = 4
    var contentView: [AnyView] = []
    //rowIndex表示行号
    func rowViews(rowIndex: Int) -> [AnyView] {
        var views = [AnyView]()
        //根据行号找到这一行的起始下标,加到views中
        for i in 0..<itemPerRow {
            let index = i + rowIndex * itemPerRow
            if index < contentView.count {
                views.append(contentView[index])
            }
        }
        return views
    }
}

最后在some view中把RowView组装起来就可以了,完整的代码如下:

struct GridContentView: View {
    var itemPerRow = 4
    var contentView: [AnyView] = []
    
    init() {
        for _ in 0..<16 {
            contentView.append(AnyView(Color.random))
        }
    }
    
    func rowCount() -> Int {
        if contentView.count % itemPerRow == 0 {
            return contentView.count / itemPerRow
        }
        return contentView.count / itemPerRow + 1
    }
    
    func rowViews(rowIndex: Int) -> [AnyView] {
        var views = [AnyView]()
        
        for i in 0..<itemPerRow {
            let index = i + rowIndex * itemPerRow
            if index < contentView.count {
                views.append(contentView[index])
            }
        }
        return views
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            ForEach(0..<rowCount()) { i in
                RowView(itemPerRow: itemPerRow, views: rowViews(rowIndex: i))
            }
        }
    }
}

contentView.swift中代码:

import SwiftUI

struct ContentView: View {
    @ObservedObject var viewModel: EmojiMemoryGame
    var body: some View {
        GridContentView()
    }
}

4.效果图

在这里插入图片描述

利用格子位置

这种方法是斯坦福大学CS193p课程所使用的,使用这种方法要用到两个结构体,,一个是GridView展示所需要的GridLayout,用于控制大小样式;一个是统一展示的GridView,用于返回some view进行展示

1. GridLayout

import SwiftUI

struct GridLayout {
    var size: CGSize
    var rowCount: Int = 0
    var columnCount: Int = 0
    
    init(itemCount: Int, nearAspectRatio desiredAspectRatio: Double = 1, in size: CGSize) {
        self.size = size
        // if our size is zero width or height or the itemCount is not > 0
        // then we have no work to do (because our rowCount & columnCount will be zero)
        guard size.width != 0, size.height != 0, itemCount > 0 else { return }
        // find the bestLayout
        // i.e., one which results in cells whose aspectRatio
        // has the smallestVariance from desiredAspectRatio
        // not necessarily most optimal code to do this, but easy to follow (hopefully)
        var bestLayout: (rowCount: Int, columnCount: Int) = (1, itemCount)
        var smallestVariance: Double?
        let sizeAspectRatio = abs(Double(size.width/size.height))
        for rows in 1...itemCount {
            let columns = (itemCount / rows) + (itemCount % rows > 0 ? 1 : 0)
            if (rows - 1) * columns < itemCount {
                let itemAspectRatio = sizeAspectRatio * (Double(rows)/Double(columns))
                let variance = abs(itemAspectRatio - desiredAspectRatio)
                if smallestVariance == nil || variance < smallestVariance! {
                    smallestVariance = variance
                    bestLayout = (rowCount: rows, columnCount: columns)
                }
            }
        }
        rowCount = bestLayout.rowCount
        columnCount = bestLayout.columnCount
    }
    
    var itemSize: CGSize {
        if rowCount == 0 || columnCount == 0 {
            return CGSize.zero
        } else {
            return CGSize(
                width: size.width / CGFloat(columnCount),
                height: size.height / CGFloat(rowCount)
            )
        }
    }
    
    func location(ofItemAt index: Int) -> CGPoint {
        if rowCount == 0 || columnCount == 0 {
            return CGPoint.zero
        } else {
            return CGPoint(
                x: (CGFloat(index % columnCount) + 0.5) * itemSize.width,
                y: (CGFloat(index / columnCount) + 0.5) * itemSize.height
            )
        }
    }
}

2. GridView

import SwiftUI

struct GridView<Item, ItemView>: View where Item: Identifiable, ItemView: View{
    var items: [Item]
    var viewForItem: (Item) -> ItemView
    
    init(_ item: [Item], viewForItem: @escaping (Item) -> ItemView) {
        self.items = item
        self.viewForItem = viewForItem
    }
    var body: some View {
        GeometryReader { geometry in
            body(for: GridLayout(itemCount: items.count, in: geometry.size))
        }
    }
    
    func body(for layout: GridLayout) -> some View {
        ForEach(items) { item in
            body(for: item, in: layout)
        }
    }
    
    func body(for item: Item, in layout: GridLayout) -> some View {
        let index = items.firstIndex(matching: item)
        return viewForItem(item)
            .frame(width: layout.itemSize.width, height: layout.itemSize.height)
            .position(layout.location(ofItemAt: index))
    }
    
    func index(of item: Item) -> Int {
        for i in 0..<items.count {
            if item.id == items[i].id {
                return i
            }
        }
        return 0 // TODO: bogus
    }
}

3. ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        GridView(colorViews()) { color in
            color
        }
    }
    func colorViews() -> [Color] {
        var contentView = [Color]()
        for _ in 0..<16 {
            contentView.append(Color.random)
        }
        return contentView
    }
}
//因为GridView里面的Item实现了Identifiable接口,所以扩展一下
extension Color: Identifiable {
    public var id: Int {
        return self.hashValue
    }
}

4. 效果图

在这里插入图片描述
使用卡片游戏的代码以及效果图

import SwiftUI

struct ContentView: View {
    @ObservedObject var viewModel: EmojiMemoryGame
    var body: some View {
        GridView(viewModel.cards) { card in
            CardView(card: card)
            .onTapGesture {
                viewModel.choose(card: card)
            }
            .padding(5)
        }
        
 //       GridContentView()
//        GridView(colorViews()) { color in
//            color
//        }
    }
    func colorViews() -> [Color] {
        var contentView = [Color]()
        for _ in 0..<16 {
            contentView.append(Color.random)
        }
        return contentView
    }
}

extension Color: Identifiable {
    public var id: Int {
        return self.hashValue
    }
}

struct CardView: View {
    var card: MemoryGame<String>.Card
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                if card.isFaceUp {
                    RoundedRectangle(cornerRadius: cornerRadius).fill(Color.white)
                    RoundedRectangle(cornerRadius: cornerRadius).stroke(lineWidth: edgeLineWidth).foregroundColor(.orange)
                    Text(card.content)
                } else {
                    RoundedRectangle(cornerRadius: cornerRadius).fill(Color.orange)
                }
            }
            .font(Font.system(size: fontSize(for: geometry.size)))
        }
        
    }
    
    // MARK: - Drawing Constants
    let cornerRadius: CGFloat = 10
    let edgeLineWidth: CGFloat = 3
    let fontScaleFactor: CGFloat = 0.75
    
    func fontSize(for size: CGSize) -> CGFloat {
        return min(size.width, size.height) * fontScaleFactor
    }
}

在这里插入图片描述

参考资料

[1] https://www.cnblogs.com/GarveyCalvin/p/swiftui-grid-view.html
[2] https://cs193p.sites.stanford.edu/

标签:GridView,return,Int,视图,contentView,SwiftUI,var,size,View
来源: https://blog.csdn.net/qq_33655674/article/details/113831234