Swift UI中Grid布局-和ZStack层叠布局示例

105 阅读2分钟

Swift UI中Grid布局-和ZStack层叠布局示例

  • Grid 和 GridRow:在SwiftUI中,Grid 是一个新的布局容器,用于创建类似表格的视图。每个 GridRow 代表一行视图元素,可以在行中放置多个视图。
  • ZStack:用于将视图叠加在一起,底层是 Color.orange,上面是一个 heart.fill 图标和文本。

示例效果图

Snipaste_2025-01-17_17-16-54.png

Swift ui 代码如下

import SwiftUI
struct ContentView: View {
    var body: some View {
        // 使用Grid布局
        Grid(){
            // 一个简单的文本视图,展示标题
            Text("Grid布局-演示页面|ZStack层叠布局 ")
                .padding() // 添加内边距
//                .frame(height:100) // 可选,设置高度
//                .background(Color.red.opacity(0.5)) // 可选,设置背景颜色
                .tint(.blue) // 设置文本颜色为蓝色
            
            // 创建一个GridRow,内容对齐方式为顶部
            GridRow(alignment: .top){
                Color.blue // 第一个颜色块,蓝色
                ZStack(content: {
                    Color.orange // 底层颜色块,橙色
                    Image(systemName: "heart.fill") // 使用系统图片:心形
                        .resizable() // 使图片可调整大小
                        .frame(width: 120, height: 120) // 设置图片大小
                        .foregroundColor(.pink) // 设置图片的前景颜色为粉色
                    Text("I Swift UI") // 显示文本
//                        .frame(width: 100,height: 100) // 可选,设置文本框大小
                        .padding(.horizontal, 10)  // 左右内边距
                        .foregroundColor(.white) // 设置字体颜色为白色
                        .background(Color.black.opacity(0.5)) // 设置背景颜色和透明度
                        .onTapGesture(perform: {
                            print("文字点击") // 点击文本时打印日志
                        })
                })
                .gridCellColumns(2) // 设置此项占用2列
            }
            
            // 创建第二行GridRow,包含三个颜色块
            GridRow{
                Color.yellow // 黄色
                Color.purple // 紫色
                Color.primary // 默认主色
            }
            
            // 创建第三行GridRow,包含一个粉色块和一个VStack
            GridRow{
                Color.pink // 粉色块
                    .gridCellColumns(2) // 占用2列
//                Color.green // 可选,绿色块
                VStack(){
                    Text("111") // 显示文本
                        .foregroundColor(.white) // 设置字体颜色为白色
                        .fontWeight(.bold) // 设置字体加粗
                        .padding() // 添加内边距
                    Button(action: {
                        print("执行按钮-点击") // 点击按钮时打印日志
                    }, label: {
                        Text("执行按钮") // 按钮的文本
                    })
                    .foregroundColor(.white) // 按钮文本颜色为白色
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity) // 设置VStack占满可用空间
                .background(Color.blue) // 设置背景颜色为蓝色
            }
        }

    }
}