You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS 16设置新TextField焦点时键盘被收起的问题求助

在Xcode 14 Beta中遇到的键盘焦点问题

在Xcode 14 beta版本中遇到问题:输入文本后键盘会被收起,但iOS 15(Xcode 13.4.1)中键盘保持显示,这是我期望的行为。我的操作是在.onSubmit中创建新条目,并以编程方式设置其焦点。

效果对比

  • iOS 15(Xcode 13.4.1)效果:
    iOS 15

  • iOS 16(Xcode 14 beta 3)效果:
    iOS 16

最小复现示例(MRE)

enum Focusable: Hashable {
    case none
    case row(id: UUID)
}

extension View {

    func sync<T: Equatable>(_ field1: Binding<T>, _ field2: FocusState<T>.Binding ) -> some View {
        self
            .onChange(of: field1.wrappedValue) {
                field2.wrappedValue = $0
            }
            .onChange(of: field2.wrappedValue) {
                field1.wrappedValue = $0
            }
    }
}

class Store: ObservableObject {
    
    struct Item: Identifiable {
        var id = UUID()
        var name: String
    }
    
    @Published var items = [Item]()
    @Published var focusedItem: Focusable?
    
    func createNewItem() {
        let newItem = Item(name: "")
        items.append(newItem)
        focusedItem = .row(id: newItem.id)
    }
}

struct ContentView: View {
    
    @FocusState private var focusedItem: Focusable?
    
    @StateObject var store = Store()
    
    var body: some View {
        NavigationView {
            List {
                ForEach($store.items) { $item in
                    TextField("", text: $item.name)
                        .focused($focusedItem, equals: .row(id: item.id))
                        .onSubmit(store.createNewItem)
                }
            }
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button("New item") {
                        store.createNewItem()
                    }
                }
            }
            .sync($store.focusedItem, $focusedItem)
        }
    }
}

内容的提问来源于stack exchange,提问作者Peter Warbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:06:27