Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a plain view in swiftUI

I'm trying to create a plain view with a background color in SwiftUI. But everything I can find are elements that are not plain views like Text, Button, Image, List, etc..

When I try to use View, it shows me following error messages:

  • 'View' cannot be constructed because it has no accessible initializers
  • 'View' Protocol can only be used as a generic constraint because it has Self or associatedType requirements

How do I create a rectangular view with background color?

like image 248
Lukas Würzburger Avatar asked Jun 06 '19 23:06

Lukas Würzburger


2 Answers

Just use the Rectangle()

As the Documentation states:

A rectangular shape aligned inside the frame of the view containing it.

Here an example of a rectangle with fixed size and background color

Rectangle()
    .size(CGSize(width: 10, height: 10))
    .foregroundColor(.red)
like image 179
Lukas Würzburger Avatar answered Nov 15 '22 01:11

Lukas Würzburger


Just in case your use case is something like creating a background for a TextField view, here's a demonstration of how I did mine

The example here will create a small view with an opaque secondary background, then render on top of it a label that signifies the user to enter a location, another white rounded rectangle, and within the white rectangle a TextField().

struct InputView : View {
    @State var text:          String

    var body: some View {
        ZStack{
            RoundedRectangle(cornerRadius: 15).frame(width: 310, height: 100)
                .foregroundColor(.secondary)
                .offset(y: -20)
            ZStack{
                RoundedRectangle(cornerRadius: 30).frame(width: 290, height: 40)
                    .foregroundColor(.white)
                TextField($text, placeholder: Text("City, State, Address")) {
                        print(self.text)
                        self.didEnter.toggle()
                    }
                        .frame(width: 220, height: 40, alignment: .leading)
                        .offset(x: -20)
                Text("Select Location:").bold().fontWeight(.medium)
                    .offset(y: -40)
                    .foregroundColor(.white)
            }
        }
    }
}
like image 26
nikoclicks Avatar answered Nov 15 '22 02:11

nikoclicks