帧监视器

一系列可用于“监视” View 并收集其相对于坐标空间的 frame(描述位置和大小的 CGRect)的对象。

如何使用

1. 使用 .coordinateSpace(name:) ViewModifier 为你的坐标空间命名。

import FrameSpy

struct ContentView: View {
    var body: some View {
        VStack(spacing: 10.0) {
            Text("Text 1")
        }
        .coordinateSpace(name: "ContentView") // the coordinate space is now named "ContentView".
    }
}

2. 声明一个“包”来收集被监视的 frame。

import FrameSpy

struct ContentView: View {
    @State var spiedFrames: SpiedFramesBag = SpiedFramesBag() // spied frames will be collected here.
    var body: some View {
        VStack(spacing: 10.0) {
            Text("Text 1")
        }
        .coordinateSpace(name: "ContentView")
    }
}

3. 使用 .spyFrame(named:inCoordinateSpaceNamed:) 监视 View 的 frame。

import FrameSpy

struct ContentView: View {
    @State var spiedFrames: SpiedFramesBag = SpiedFramesBag()
    var body: some View {
        VStack(spacing: 10.0) {
            Text("Text 1")
               .spyFrame(named: "text-1", inCoordinateSpaceNamed: "ContentView")  // This `Text`s frame is now "spied" in the coordinate space "ContentView". The spied frame's name is "text-1"
        }
        .coordinateSpace(name: "ContentView")
    }
}

4. 使用 .collectSpiedFrames(into:) ViewModifier 将被监视的 frame 收集到步骤 1 中声明的包中。

import FrameSpy

struct ContentView: View {
    @State var spiedFrames: SpiedFramesBag = SpiedFramesBag()
    var body: some View {
        VStack(spacing: 10.0) {
            Text("Text 1")
                .spyFrame(named: "text-1", inCoordinateSpaceNamed: "ContentView")
        }
        .coordinateSpace(name: "ContentView")
        .collectSpiedFrames(into: $spiedFrames) // The spied frames will be collected into `$spiedFrames`
    }
}

Text 的 frame 将作为 spiedFrames["text-1"] 可用。 记住这个值是 Optional 的,可能并非总是可用。