在SwiftUI中获取任意视图的尺寸

PHOTO EMBED

Wed Feb 08 2023 11:54:17 GMT+0000 (Coordinated Universal Time)

Saved by @zelda #swift #swiftui

//
//  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))
    }
}
content_copyCOPY