“静态方法‘buildBlock’要求‘CGRect’符合‘View’”

Joh*_*nas 0 cgrect swift swiftui

我的代码看起来像这样:

import SwiftUI

struct MainView: View {
    var body: some View {
        CGRect(x: 20, y: 20, width: 100, height: 100)
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到错误:

Static method 'buildBlock' requires that 'CGRect' conform to 'View'
Run Code Online (Sandbox Code Playgroud)

如何在 SwiftUI 中使用 CGRect?

Asp*_*eri 6

可能你想要这个

struct MainView: View {
    var body: some View {
        Rectangle()
          .frame(width: 100, height: 100)
    }
}
Run Code Online (Sandbox Code Playgroud)

在 SwiftUI 中,我们应该只在 中放置视图body,而不是绘制一些东西。

注意:根据需要,屏幕上的视图布局有不同的变体,但我建议避免位置硬编码(如 x:20、y:20),因为它会在不同的设备上给出不同的结果。