SwiftUI 选择器 onChange 或等效的? [英] SwiftUI Picker onChange or equivalent?

查看:47
本文介绍了SwiftUI 选择器 onChange 或等效的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Picker 更改时更改另一个不相关的 @State 变量,但是没有 onChanged 并且无法放置选择器 @State 上的 didSet.还有其他方法可以解决这个问题吗?

I want to change another unrelated @State variable when a Picker gets changed, but there is no onChanged and it's not possible to put a didSet on the pickers @State. Is there another way to solve this?

推荐答案

这是我刚刚决定使用的... (部署目标 iOS 13)

Here is what I just decided to use... (deployment target iOS 13)

struct MyPicker: View {
    @State private var favoriteColor = 0

    var body: some View {
        Picker(selection: $favoriteColor.onChange(colorChange), label: Text("Color")) {
            Text("Red").tag(0)
            Text("Green").tag(1)
            Text("Blue").tag(2)
        }
    }

    func colorChange(_ tag: Int) {
        print("Color tag: \(tag)")
    }
}

使用这个助手

extension Binding {
    func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> {
        return Binding(
            get: { self.wrappedValue },
            set: { selection in
                self.wrappedValue = selection
                handler(selection)
        })
    }
}

如果您的部署目标设置为 iOS 14 或更高版本 -- Apple 已经为 View 提供了一个内置的 onChange 扩展,它可以改为这样使用(感谢@Jeremy):

If your deployment target is set to iOS 14 or higher -- Apple has provided a built in onChange extension to View, which can be used like this instead (Thanks @Jeremy):

Picker(selection: $favoriteColor, label: Text("Color")) {
    // ..
}
.onChange(of: favoriteColor) { tag in print("Color tag: \(tag)") }

这篇关于SwiftUI 选择器 onChange 或等效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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