swiftswiftuicgrect

"Static method 'buildBlock' requires that 'CGRect' conform to 'View'"


My Code looks something like this:

import SwiftUI

struct MainView: View {
    var body: some View {
        CGRect(x: 20, y: 20, width: 100, height: 100)
    }
}

However, I get the error:

Static method 'buildBlock' requires that 'CGRect' conform to 'View'

How can I use CGRect with SwiftUI?


Solution

  • Probably you wanted this

    struct MainView: View {
        var body: some View {
            Rectangle()
              .frame(width: 100, height: 100)
        }
    }
    

    in SwiftUI we should just place views in body, instead of drawing something.

    Note: there are different variants for view layout on screen, depending on needs, but I'd recommend to avoid position hardcoding (like x:20, y:20), because it will give different result on different devices.