With the below code, if we run on simulator the editing seems to work.
However in the swift UI preview it does not seem to be editing. It shows "Scan Text" but not allow me to enter text through keyboard.
import SwiftUI
struct DetailView: View {
@Binding var editingText: String
var body: some View {
VStack {
TextEditor(text: $editingText).disabled(false)
}
}
}
struct DetailView_Previews: PreviewProvider {
@State static var text = "Enter some text"
static var previews: some View {
DetailView(editingText: $text)
}
}
Although there isn't any documentation that clarifies this, it seems to be that @State
properties don't work because the previews
property of a preview doesn't act the same as the body
property of a regular view.
You need to create a container view and use that view as a preview. This way, you can control the view's state. Check Structure your app for SwiftUI previews WWDC2020 session.
struct DetailView: View {
@Binding var editingText: String
var body: some View {
VStack {
TextEditor(text: $editingText).disabled(false)
}
}
}
struct DetailView_Previews: PreviewProvider {
struct DetailViewPreview: View {
@State var text = "Enter some text"
var body: some View {
DetailView(editingText: $text)
}
}
static var previews: some View {
DetailViewPreview()
}
}
Another workaround that seems to work is to create the @Binding
property with the init(get:set:) method.
struct DetailView_Previews: PreviewProvider {
static var text = "Enter some text"
static var editingText = Binding(
get: {
text
},
set: {
text = $0
}
)
static var previews: some View {
DetailView(editingText: editingText)
}
}