Reputation: 255
Trying to create a interface that users can write a string of text that wraps around on the screen.
I created a SwiftUI page called 'TextArea' that I can call on another page when I need it. Since TextEditor cant put placeholder text. I needed to create one, this is my code here that I got from other users.
import SwiftUI
import UIKit
struct TextArea: View {
@Binding var text: String
let placeholder: String
init(_ placeholder: String, text: Binding<String>) {
self.placeholder = placeholder
self._text = text
UITextView.appearance().backgroundColor = .clear
}
var body: some View {
ZStack(alignment: .topLeading) {
if text.isEmpty {
Text(placeholder)
.foregroundColor(Color(.placeholderText))
.padding(.horizontal, 8)
.padding(.vertical, 12)
}
TextEditor(text: $text)
.padding(4)
}
.font(.body)
}
}
Then on another SwiftUI page I call it with this block of code.
TextArea("What's Happening", text: $caption)
At the top of that page I establish it
@State private var caption = ""
The code compiles with no errors and builds no problem in the emulator. When I run the app, there is no placeholder text. The TextEditor works fine and as expected. The only thing that is missing is the placeholder text.
Thanks in advance!
Upvotes: 2
Views: 1654
Reputation: 31
The code might be a bit clearer if we get rid of init(), because the placeholder will cover the TextEditor after swapping views, and we don't need to worry about the background UITextView (it's part of the TextEditor).
struct TextArea: View {
@Binding var text: String
let placeholder: String
init(_ placeholder: String, text: Binding<String>) {
self.placeholder = placeholder
self._text = text
UITextView.appearance().backgroundColor = .clear
}
var body: some View {
ZStack(alignment: .topLeading) {
TextEditor(text: $text)
.padding(4)
if text.isEmpty {
Text(placeholder)
.foregroundColor(Color(.placeholderText))
.padding(.horizontal, 8)
.padding(.vertical, 12)
}
}
.font(.body)
}
}
Upvotes: 0
Reputation: 6500
ZStack
place view from bottom to top.
so that swap your placeholder view and TextEditor.
struct TextArea: View {
@Binding var text: String
let placeholder: String
init(_ placeholder: String, text: Binding<String>) {
self.placeholder = placeholder
self._text = text
UITextView.appearance().backgroundColor = .clear
}
var body: some View {
ZStack(alignment: .topLeading) {
TextEditor(text: $text) // <= Here
.padding(4)
if text.isEmpty {
Text(placeholder)
.foregroundColor(Color(.placeholderText))
.padding(.horizontal, 8)
.padding(.vertical, 12)
}
}
.font(.body)
}
}
Upvotes: 4