[英]How can I fix disabled text editor focusing bug in SwiftUI
I think there's a bug that disabled text editor is focussed when I get in and out into another tab.我认为当我进出另一个选项卡时,禁用的文本编辑器会集中在一个错误上。 I want to totally disable text editors but I don't know how.我想完全禁用文本编辑器,但我不知道怎么做。 Seeing is believing.眼见为实。
struct TabViewWithTextEditor: View {
var body: some View {
TabView {
TextEditors()
.tabItem {
Image(systemName: "text.bubble")
Text("Text Editor")
}
AnotherView()
.tabItem {
Image(systemName: "shippingbox")
Text("Empty View")
}
}
}
}
struct TextEditors: View {
@State var textA: String = "Hello World"
@State var textB: String = "Placeholder"
@State var enabled: Bool = true
init() {
UITextView.appearance().backgroundColor = .clear // To apply background color.
}
var body: some View {
VStack {
Text("Text Editor")
TextEditor(text: $textA)
.background(enabled ? .gray : .red)
.foregroundColor(.black)
.disabled(!enabled)
TextEditor(text: $textB)
.background(enabled ? .yellow : .red)
.foregroundColor(.black)
.disabled(!enabled)
Toggle("Enable Text Editors", isOn: $enabled)
}
.padding(30)
}
}
struct AnotherView: View {
var body: some View {
Text("Empty View")
}
}
And it looks like它看起来像
It looks like the issue is due to TextEditor
(or UITextView
at backend) preserves focus, probably due to a bug.看起来问题是由于TextEditor
(或后端的UITextView
)保留了焦点,可能是由于错误。
Here is safe workaround - remove focus forcefully before disable这是安全的解决方法 - 在禁用之前强行移除焦点
Tested with Xcode 13.4 / iOS 15.5使用 Xcode 13.4 / iOS 15.5 测试
@FocusState private var focused: Bool
var isEditing: Binding<Bool> {
Binding(get: { enabled } , set: {
if !$0 {
focused = false // << here !!
}
enabled = $0
})
}
// ...
Toggle("Enable Text Editors", isOn: isEditing)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.