状态更改时如何执行操作?

时间:2019-06-11 19:41:15

标签: ios swift state swiftui

enum SectionType: String, CaseIterable {
    case top = "Top"
    case best = "Best"
}

struct ContentView : View {
    @State private var selection: Int = 0

    var body: some View {
        SegmentedControl(selection: $selection) {
            ForEach(SectionType.allCases.identified(by: \.self)) { type in
                Text(type.rawValue).tag(type)
            }
        }
    }
}

如何运行代码(例如print("Selection changed to \(selection)")状态更改时的$selection?我浏览了文档,却找不到任何东西。

8 个答案:

答案 0 :(得分:21)

如果您具有更新@Binding的组件,则这是另一种选择。而不是这样做:

Component(selectedValue: self.$item, ...)

您可以执行此操作,并获得更大的控制权:

Component(selectedValue: Binding(
    get: { self.item },
    set: { (newValue) in
              self.item = newValue
              // now do whatever you need to do once this has changed
    }), ... )

通过这种方式,您可以获得绑定的好处,并且可以检测到Component何时更改了值。

答案 1 :(得分:16)

iOS 14.0 +

您可以使用onChange(of:perform:)修饰符,如下所示:

struct ContentView: View {
    
    @State private var isLightOn = false

    var body: some View {
        Toggle("Light", isOn: $isLightOn)
            .onChange(of: isLightOn) { value in
                if value {
                    print("Light is now on!")
                } else {
                    print("Light is now off.")
                }
            }
    }
}

iOS 13.0 +

以下内容是Binding的扩展,因此只要值更改,就可以执行闭包。

extension Binding {
    
    /// When the `Binding`'s `wrappedValue` changes, the given closure is executed.
    /// - Parameter closure: Chunk of code to execute whenever the value changes.
    /// - Returns: New `Binding`.
    func onUpdate(_ closure: @escaping () -> Void) -> Binding<Value> {
        Binding(get: {
            wrappedValue
        }, set: { newValue in
            wrappedValue = newValue
            closure()
        })
    }
}

例如这样使用:

struct ContentView: View {
    
    @State private var isLightOn = false
    
    var body: some View {
        Toggle("Light", isOn: $isLightOn.onUpdate(printInfo))
    }
    
    private func printInfo() {
        if isLightOn {
            print("Light is now on!")
        } else {
            print("Light is now off.")
        }
    }
}

此示例不需要 使用单独的函数。您只需要关闭即可。

答案 2 :(得分:14)

在iOS 14中,现在可以像这样使用onChange修饰符:

SegmentedControl(selection: $selection) {
    ForEach(SectionType.allCases.identified(by: \.self)) { type in
        Text(type.rawValue).tag(type)
    }
}
.onChange(of: selection) { value in
    print("Selection changed to \(selection)")
}

答案 3 :(得分:3)

SwiftUI 1和2(iOS 13和14)

您可以使用onReceive

import Combine
import SwiftUI

struct ContentView: View {
    @State private var selection = false

    var body: some View {
        Toggle("Selection", isOn: $selection)
            .onReceive(Just(selection)) { selection in
                // print(selection)
            }
    }
}

答案 4 :(得分:1)

并没有真正回答您的问题,但是这是设置SegmentedControl的正确方法(因为它看起来很丑,所以不想将其作为注释发布)。将您的ForEach版本替换为以下代码:

ForEach(0..<SectionType.allCases.count) { index in 
    Text(SectionType.allCases[index].rawValue).tag(index)
}

用枚举用例或什至字符串标记视图会使它的行为不充分-选择不起作用。

您可能还想在SegmentedControl声明后添加以下内容,以确保选择有效:

Text("Value: \(SectionType.allCases[self.selection].rawValue)")

body的完整版本:

var body: some View {
    VStack {
        SegmentedControl(selection: self.selection) {
            ForEach(0..<SectionType.allCases.count) { index in
                Text(SectionType.allCases[index].rawValue).tag(index)
                }
            }

        Text("Value: \(SectionType.allCases[self.selection].rawValue)")
    }
}

关于您的问题–我尝试将didSet观察者添加到selection,但在尝试构建时,它使Xcode编辑器崩溃并生成“ Segmentation fault:11”错误。

答案 5 :(得分:1)

目前,您不能在this.onChange = editorState => { this.setState({ editorState, editorContentHtml: stateToHTML(editorState.getCurrentContent()) }); }; 上使用didSet,但是可以在@State属性上使用。我的解决方案是像这样创建BindableObject

BindableObject

然后像这样使用它:

import SwiftUI
import Combine

final class SelectionStore: BindableObject {
    var didChange = PassthroughSubject<SelectionStore, Never>()

    var selection: SectionType = .top {
        didSet {
            print("Selection changed to \(selection)")
        }
    }
}

答案 6 :(得分:0)

您可以使用绑定

let textBinding = Binding<String>(
    get: { /* get */ },
    set: { /* set $0 */ }
)

答案 7 :(得分:-1)

我喜欢通过将数据移动到结构中来解决这个问题:

struct ContentData {
    var isLightOn = false {
        didSet {
            if isLightOn {
                print("Light is now on!")
            } else {
                print("Light is now off.")
            }
            // you could update another var in this struct based on this value
        }
    }
}

struct ContentView: View {
    
    @State private var data = ContentData()

    var body: some View {
        Toggle("Light", isOn: $data.isLightOn)
    }
}

这种方式的优点是,如果您决定根据 didSet 中的新值更新结构中的另一个 var,并且您使绑定具有动画效果,例如isOn: $data.isLightOn.animation() 然后您更新的任何使用其他变量的视图都将在切换过程中对其更改进行动画处理。如果您使用 onChange,则不会发生这种情况。

例如这里列表排序顺序更改动画:

import SwiftUI

struct ContentData {
    var ascending = true {
        didSet {
            sort()
        }
    }
    
    var colourNames = ["Red", "Green", "Blue", "Orange", "Yellow", "Black"]
    
    init() {
        sort()
    }
    
    mutating func sort(){
        if ascending {
            colourNames.sort()
        }else {
            colourNames.sort(by:>)
        }
    }
}


struct ContentView: View {
    @State var data = ContentData()
    
    var body: some View {
        VStack {
            Toggle("Sort", isOn:$data.ascending.animation())
            List(data.colourNames, id: \.self) { name in
                Text(name)
            }
        }
        .padding()
    }
}