【问题标题】:SwiftUI - TextField is disabled (not editable) when placed in List on macOSSwiftUI - TextField 在 macOS 上的 List 中被禁用(不可编辑)
【发布时间】:2019-06-24 08:46:03
【问题描述】:

TextField 在 macOS 上的 List 中被禁用(不可编辑)。当为 iOS 构建相同的代码并在模拟器中运行时,它会按预期工作。

这是一个错误,还是我遗漏了什么?

代码:

struct ContentView : View {

    @State private var text: String = ""

    var body: some View {
        VStack {
            List {
                // TextField is not editable when this code is ran on macOS
                TextField($text, placeholder: Text("Entry text"))
                Text("Entered text: \(text)")
            }
            // TextField is editable on both macOS as well as iOS
            TextField($text, placeholder: Text("Entry text"))
        }
    }
}

【问题讨论】:

    标签: ios macos swiftui


    【解决方案1】:

    那是因为该列表通过点击来驱动选择,而您在这里没有使用。 TextField 在 macOS 上的列表中只有当它所在的行有选择时才可编辑。

    如果您将代码更改为这样的内容

    struct ContentView : View {
        @State private var text: String = "Hello"
        @State private var selection: Int? = nil
        var body: some View {
            VStack {
                List(selection: $selection) {
                    ForEach(0..<5) { _ in
                        TextField(self.$text)
                    }
                }
                TextField($text)
            }
        }
    }
    
    

    然后运行代码,第一次单击单元格将使其被选中,第二次单击将使文本字段获得焦点。

    【讨论】:

    • 正在搜索这个,但它不适用于 XCode 11.4 和 Swift5.2。请问可以修吗?
    【解决方案2】:

    使用以下代码创建 TextField

    struct ContentView : View {
        @State private var helloText: String = "Hello"
        @State private var selection: Int? = nil
        var body: some View {
            VStack {
                List(selection: $selection) {
                    ForEach(0..<5) { _ in
                        TextField(.constant(self.helloText), placeholder: Text("Entry text")).textFieldStyle(.roundedBorder)
                    }
                }
    
            }
        }
    }
    

    【讨论】:

    • 这里也一样。正在搜索这个,但它不适用于 XCode 11.4 和 Swift5.2。请问可以修吗?
    猜你喜欢
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    相关资源
    最近更新 更多