简体   繁体   中英

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?

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)

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

As suggested in another answer, you could use Shape like Rectangle() and set it's size and foregroundColor :

Rectangle()
    .size(CGSize(width: 10, height: 10))
    .foregroundColor(.blue)

But I think using Color directly is simpler:

Color.blue
    .frame(width: 10, height: 10)

This is another way of creating something like a UIView . In SwiftUI, every primitive view works like a UIView.

struct CustomView : View {

    var body: some View {
        ZStack{
            Color.red.frame(width: 300, height: 300)
            Text("This is view")
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM