Preview:
//
//  MeasureSizeView.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/2/8.
//

import SwiftUI

// 获取视图的尺寸
struct MeasureSizeView: View {
    // 视图的宽度
    @State private var viewWidth: Double = 0
    
    var body: some View {
        VStack {
            // 获取文本视图的宽度
            Text("Hello, World!")
                .measureSize { size in
                    viewWidth = size.width
                }
            // 展示文本视图的宽度
            Text(viewWidth, format: .number)
        }
    }
}

struct MeasureSizeView_Previews: PreviewProvider {
    static var previews: some View {
        MeasureSizeView()
    }
}

// 自定义视图尺寸修改器
struct MeasureSizeModifer: ViewModifier {
    let callback: (CGSize) -> Void
    
    func body(content: Content) -> some View {
        content
            .background {
                // 通过几何阅读器获取视图的尺寸
                GeometryReader { proxy in
                    Color.clear
                        .onAppear {
                            callback(proxy.size)
                        }
                }
            }
    }
}

extension View {
    // 自定义获取视图尺寸的修饰符
    func measureSize(_ callback: @escaping (CGSize) -> Void) -> some View {
        modifier(MeasureSizeModifer(callback: callback))
    }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter