簡體   English   中英

如何檢測 TextField 何時在 iOS 的 SwiftUI 中失去焦點?

[英]How to detect when a TextField loses the focus in SwiftUI for iOS?

TextField("Name", text: $name)

我找到了這個方法

func focusable(_ isFocusable: Bool = true, onFocusChange: @escaping (Bool) -> Void = { _ in }) -> some View

但它僅適用於 MacOS,我該如何為 iOS 做類似的事情?

您可以使用文本字段中存在的初始化程序init(_:text:onEditingChanged:onCommit:) 當您開始編輯和結束編輯時,您將觸發一個動作。 您可以在下面找到最小的示例。

import SwiftUI

struct ContentView: View {
    @State private var greeting: String = "Hello world!"
    var body: some View {
        TextField("Welcome", text: $greeting, onEditingChanged: { (editingChanged) in
            if editingChanged {
                print("TextField focused")
            } else {
                print("TextField focus removed")
            }
        })
    }
}

希望這可以幫助。

iOS 15

在 iOS 15 我們可以使用onFocus

TextField("Name", text: $name)
    .onFocus { isFocused in
        // ...
    }

這個解決方案對我有用。 如果您在應用程序中有幾種類型的文本字段,您可以輕松地重用此代碼並進行修改。 焦點僅適用於當前領域,因為您不能專注於一個領域 - 這是一個很好的解決方案。 (在 Xcode 13.2 中測試)

struct MyTextField: View {
    
    let placeholder: String
    
    @FocusState private var focusState: Bool
    
    @Binding var text: String
    @Binding var enabled: Bool
    
    @State private var isFocused: Bool = false
    
    var body: some View {
        TextField(placeholder, text: $text)
            .focused($focusState)
            .onChange(of: focusState, perform: { newValue in
                print(newValue)
                isFocused = newValue
            })
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM