如何检测 SwiftUI 中 TextField 的实时更改? [英] How to detect live changes on TextField in SwiftUI?

查看:30
本文介绍了如何检测 SwiftUI 中 TextField 的实时更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 TextField,它像这样绑定到状态位置",

I have a simple TextField that binds to the state 'location' like this,

TextField("Search Location", text: $location)

我想在每次这个字段改变时调用一个函数,就像这样:

I want to call a function each time this field changes, something like this:

TextField("Search Location", text: $location) {
   self.autocomplete(location)
}

然而这行不通.我知道有回调 onEditingChanged - 但是这似乎只有在聚焦该字段时才会触发.

However this doesn't work. I know that there are callbacks, onEditingChanged - however this only seems to be triggered when the field is focussed.

如何在每次更新字段时调用此函数?

How can I get this function to call each time the field is updated?

推荐答案

您可以使用自定义闭包创建绑定,如下所示:

You can create a binding with a custom closure, like this:

struct ContentView: View {
    @State var location: String = ""

    var body: some View {
        let binding = Binding<String>(get: {
            self.location
        }, set: {
            self.location = $0
            // do whatever you want here
        })

        return VStack {
            Text("Current location: (location)")
            TextField("Search Location", text: binding)
        }

    }
}

这篇关于如何检测 SwiftUI 中 TextField 的实时更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆