【发布时间】:2020-02-23 19:32:46
【问题描述】:
最小的可重现示例:
在SceneDelegate.swift:
let contentView = Container()
在ContentView.swift:
struct SwiftUIView: View {
@State var text: String = ""
var body: some View {
VStack {
CustomTextFieldView(text: $text)
}
}
}
struct Container: View {
@State var bool: Bool = false
@State var text: String = ""
var body: some View {
Button(action: {
self.bool.toggle()
}) {
Text("Sheet!")
}
.sheet(isPresented: $bool) {
SwiftUIView()
}
}
}
在CustomTextField.swift:
struct CustomTextFieldView: View {
@Binding var text: String
@State var editing: Bool = false
var body: some View {
Group {
if self.editing {
textField
.background(Color.red)
} else {
ZStack(alignment: .leading) {
textField
.background(Color.green)
Text("Placeholder")
}
}
}
.onTapGesture {
withAnimation {
self.editing = true
}
}
}
var textField: some View {
TextField("", text: $text)
}
问题:
运行上述代码并聚焦文本字段后,应用程序崩溃。我注意到的一些事情:
- 如果我删除
withAnimation代码或CustomTextField文件中的ZStack,应用不会崩溃,但 TextField 会失去焦点。 - 如果我删除
SwiftUIView中的VStack,应用不会崩溃,但 TextField 会失去焦点。 - 如果我使用 NavigationLink 或在没有工作表的情况下显示 TextField,应用不会崩溃,但 TextField 会失去焦点。
问题:
- 这是当前版本的 SwiftUI 的问题吗?
- 是否有使用 SwiftUI 解决此问题的方法?我想远离 尽可能多地查看可表示对象。
- 由于状态更改而重新计算正文后,如何保持 TextField 的焦点?
【问题讨论】: