gpt4 book ai didi

swift - 使用 Combine 框架的按钮操作

转载 作者:行者123 更新时间:2023-11-28 13:23:14 31 4
gpt4 key购买 nike

为按钮操作事件实现响应式编程的最佳方法是什么?

关于指南和示例,我只找到了带有 SwiftUI @State 的示例。

我的意思是这样的:

@State var isVisible = false

....

Button(action: {
self.isVisible.toggle()
}

....

if isVisible {
Text("texty text")
}

但是如果我想执行后台任务怎么办?显而易见的方法是在 Button.action( 中调用 viewModel?.pleaseDoAction(),并创建一个在 pleaseDoAction() 中触发的自定义 Subject >:

final class ViewModel {
func pleaseDoAction() {
mySubject.send("some")
}
}

但这是 SwiftUI + Combine 的正确架构方法吗?简而言之,按钮操作应该是 Publisher,但它不是。

最佳答案

@Partha G 的 ViewModel 方法可能是最合适的,但这里有一个不需要 View 模型的简单方法。

作为预警,如果您的 View 这样做,这种方法可能无法与 SwiftUI View 刷新很好地融合。但对于这个非常简单的案例,它似乎运行良好。

  1. 向您的 View 添加一个 PassthroughSubject,如下所示:
// Your view with a button:

import SwiftUI
import Combine

struct MyAwesomeView: View {

public var buttonPressedSubject = PassthroughSubject<Void, Never>()

var body: some View {

Button("Push This Button", action: {
self.buttonPressedSubject.send()
})
}
}

  1. 像这样订阅和使用该主题:
import Combine

class A {

private var cancelBag = Set<AnyCancellable>()

private let myView: MyAwesomeView

init(view: MyAwesomeView) {
self.myView = view

myView.buttonPressedSubject
.sink { (_) in
print("The button was pressed.")
}
.store(in: &cancelBag)

}
}
  1. Playground 中的示例用法:

// <#Copy-paste code from above here#>
import PlaygroundSupport

let playgroundView = MyAwesomeView()
let playgroundExample = A(view: playgroundView)
PlaygroundPage.current.setLiveView(playgroundView)

关于swift - 使用 Combine 框架的按钮操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792747/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com