I want to make a simple form and change the background color of a text field, but Xcode provide me .background(background: View)
, etc option but not .background(Color()
).
Asked
Active
Viewed 1.4k times
-3

Mojtaba Hosseini
- 95,414
- 31
- 268
- 278

subhangi pawar
- 451
- 2
- 7
- 16
-
2Post the code, not image. – Mojtaba Hosseini Nov 06 '19 at 10:09
-
3**DO NOT post images of code, data, error messages, etc.** - copy or type the text into the question. https://stackoverflow.com/help/how-to-ask – Rob Nov 07 '19 at 00:55
3 Answers
5
Color
is conformed to View
. So you can use it like any other View
. The issue with your code is you add cornerRadius
inside the background
modifier. It should be out like this:
TextField("Title", text: .constant("text"))
.background(Color.red)
.cornerRadius(5)

Mojtaba Hosseini
- 95,414
- 31
- 268
- 278
-
Nope - doesn't work for TextField. Correct answer here: https://stackoverflow.com/questions/62848276/change-background-color-of-texteditor-in-swiftui – Antonín Karásek Jan 08 '21 at 09:59
-
This is the answer to the question. The title is misleading. @AntonínKarásek – Mojtaba Hosseini Jan 08 '21 at 10:04
3
Try below code.
struct ContentView: View {
@State var name: String = ""
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text("NAME").font(.headline)
TextField("Enter some text", text: $name)
.padding(.horizontal , 15)
.frame(height: 40.0)
.background(Color(red: 239/255, green: 243/255, blue: 244/255))
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color.gray.opacity(0.3), lineWidth: 1)
)
}.padding(.horizontal , 15)
}
}

Rohit Makwana
- 4,337
- 1
- 21
- 29
-2
import SwiftUI
struct ContentView: View {
@State var name: String = ""
var body: some View {
VStack {
TextField("Enter some text", text: $name)
.background(Color.red)
}
}
}

Andrew
- 26,706
- 9
- 85
- 101

Bhavesh Sachala
- 17
- 2
-
1When posting answers it is best to explain how your answer solves the question askers issue. – App Dev Guy Nov 07 '19 at 07:51
-
2This is not the correct solution either since when you then click on the TextField the text area will have the same color. – Mattia Righetti Apr 26 '20 at 17:16