Oth*_*hyn 2 ios swift swiftui observedobject viewbuilder
我已经研究了几天,搜索了 Swift 和 SwiftUI 文档、SO、论坛等,但似乎找不到答案。
这是问题所在;
我有一个 SwiftUI 自定义视图,它对远程资源的自定义 API 请求类进行一些状态确定。View 处理显示加载状态和失败状态,以及它的主体内容通过 ViewBuilder 传递,这样如果来自 API 的状态成功并且资源数据被加载,它将显示页面的内容。
问题是,当子类 ObservedObject 更新时,ViewBuilder 内容不会重新渲染。对象更新以响应 UI(当按下按钮时等),但 UI 永远不会重新渲染/更新以反映子类 ObservedObject 内的更改,例如,子类 ObservedObject 中数组后面的 ForEach 在以下情况下不会刷新数组内容改变。如果我将它移出自定义视图,ForEach 将按预期工作。
我可以确认代码编译并运行。Observers 和debugPrint()
's 始终显示ApiObject
正在正确更新状态,并且视图ApiState
完全正确地反映了更改。它只是Content
ViewBuilder 的。我假设是因为 ViewBuilder 只会被调用一次。
编辑:上面的段落应该是提示,ApiState
更新正确,但是在将大量日志记录到应用程序之后,UI 没有监听子类 ObservedObject 的发布。属性在变化,状态也在变化,但 UI 并没有对其做出反应。另外,下一句被证明是错误的,我在 VStack 中再次测试,组件仍然没有重新渲染,这意味着我找错了地方!
如果是这种情况,VStack
其他此类元素如何解决此问题?还是因为我ApiObjectView
在状态更改时被重新渲染,导致子视图“重置”?尽管在这种情况下,我希望它能够接受新数据并按预期工作,但它永远不会重新渲染。
有问题的代码是在CustomDataList.swift
和ApiObjectView.swift
下方。我已经发表评论指出正确的方向。
这是示例代码;
// ApiState.swift
// Stores the API state for where the request and data parse is currently at.
// This drives the ApiObjectView state UI.
import Foundation
enum ApiState: String
{
case isIdle
case isFetchingData
case hasFailedToFetchData
case isLoadingData
case hasFailedToLoadData
case hasUsableData
}
Run Code Online (Sandbox Code Playgroud)
// ApiObject.swift
// A base class that the Controllers for the app extend from.
// These classes can make data requests to the remote resource API over the
// network to feed their internal data stores.
class ApiObject: ObservableObject
{
@Published var apiState: ApiState = .isIdle
let networkRequest: NetworkRequest = NetworkRequest(baseUrl: "https://api.example.com/api")
public func apiGetJson<T: Codable>(to: String, decodeAs: T.Type, onDecode: @escaping (_ unwrappedJson: T) -> Void) -> Void
{
self.apiState = .isFetchingData
self.networkRequest.send(
to: to,
onComplete: {
self.apiState = .isLoadingData
let json = self.networkRequest.decodeJsonFromResponse(decodeAs: decodeAs)
guard let unwrappedJson = json else {
self.apiState = .hasFailedToLoadData
return
}
onDecode(unwrappedJson)
self.apiState = .hasUsableData
},
onFail: {
self.apiState = .hasFailedToFetchData
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
// DataController.swift
// This is a genericised example of the production code.
// These controllers build, manage and serve their resource data.
// Subclassed from the ApiObject, inheriting ObservableObject
import Foundation
import Combine
class CustomDataController: ApiObject
{
@Published public var customData: [CustomDataStruct] = []
public func fetch() -> Void
{
self.apiGetJson(
to: "custom-data-endpoint ",
decodeAs: [CustomDataStruct].self,
onDecode: { unwrappedJson in
self.customData = unwrappedJson
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个有重新绘制它的问题的视图ForEach
上ObservedObject
改变其绑定的数组属性。
// CustomDataList.swift
// This is the SwiftUI View that drives the content to the user as a list
// that displays the CustomDataController.customData.
// The ForEach in this View
import SwiftUI
struct CustomDataList: View
{
@ObservedObject var customDataController: CustomDataController = CustomDataController()
var body: some View
{
ApiObjectView(
apiObject: self.customDataController,
onQuit: {}
) {
List
{
Section(header: Text("Custom Data").padding(.top, 40))
{
ForEach(self.customDataController.customData, id: \.self, content: { customData in
// This is the example that doesn't re-render when the
// customDataController updates its data. I have
// verified via printing at watching properties
// that the object is updating and pushing the
// change.
// The ObservableObject updates the array, but this ForEach
// is not run again when the data is changed.
// In the production code, there are buttons in here that
// change the array data held within customDataController.customData.
// When tapped, they update the array and the ForEach, when placed
// in the body directly does reflect the change when
// customDataController.customData updates.
// However, when inside the ApiObjectView, as by this example,
// it does not.
Text(customData.textProperty)
})
}
}
.listStyle(GroupedListStyle())
}
.navigationBarTitle(Text("Learn"))
.onAppear() {
self.customDataController.fetch()
}
}
}
struct CustomDataList_Previews: PreviewProvider
{
static var previews: some View
{
CustomDataList()
}
}
Run Code Online (Sandbox Code Playgroud)
这是有问题的自定义视图,不会重新呈现其内容。
// ApiObjectView
// This is the containing View that is designed to assist in the UI rendering of ApiObjects
// by handling the state automatically and only showing the ViewBuilder contents when
// the state is such that the data is loaded and ready, in a non errornous, ready state.
// The ViewBuilder contents loads fine when the view is rendered or the state changes,
// but the Content is never re-rendered if it changes.
// The state renders fine and is reactive to the object, the apiObjectContent
// however, is not.
import SwiftUI
struct ApiObjectView<Content: View>: View {
@ObservedObject var apiObject: ApiObject
let onQuit: () -> Void
let apiObjectContent: () -> Content
@inlinable public init(apiObject: ApiObject, onQuit: @escaping () -> Void, @ViewBuilder content: @escaping () -> Content) {
self.apiObject = apiObject
self.onQuit = onQuit
self.apiObjectContent = content
}
func determineViewBody() -> AnyView
{
switch (self.apiObject.apiState) {
case .isIdle:
return AnyView(
ActivityIndicator(
isAnimating: .constant(true),
style: .large
)
)
case .isFetchingData:
return AnyView(
ActivityIndicator(
isAnimating: .constant(true),
style: .large
)
)
case .isLoadingData:
return AnyView(
ActivityIndicator(
isAnimating: .constant(true),
style: .large
)
)
case .hasFailedToFetchData:
return AnyView(
VStack
{
Text("Failed to load data!")
.padding(.bottom)
QuitButton(action: self.onQuit)
}
)
case .hasFailedToLoadData:
return AnyView(
VStack
{
Text("Failed to load data!")
.padding(.bottom)
QuitButton(action: self.onQuit)
}
)
case .hasUsableData:
return AnyView(
VStack
{
self.apiObjectContent()
}
)
}
}
var body: some View
{
self.determineViewBody()
}
}
struct ApiObjectView_Previews: PreviewProvider {
static var previews: some View {
ApiObjectView(
apiObject: ApiObject(),
onQuit: {
print("I quit.")
}
) {
EmptyView()
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果ApiObjectView
不使用 并且内容直接放在视图中,则上述所有代码都可以正常工作。
但是,这对于代码重用和架构来说是可怕的,这种方式既漂亮又整洁,但不起作用。
有没有其他方法可以解决这个问题,例如通过 aViewModifier
或View
扩展名?
对此的任何帮助将不胜感激。
正如我所说,我似乎无法找到任何有此问题的人或任何在线资源,可以为我指明解决此问题的正确方向,或可能导致此问题的原因,例如 ViewBuilder 文档中所述。
编辑:为了抛出一些有趣的东西,我已经在 中添加了一个倒数计时器CustomDataList
,它每 1 秒更新一个标签。如果该计时器对象更新了文本,则重新渲染视图,但仅当显示倒计时时间的标签上的文本更新时才会重新渲染。
把我的头发拔了一个星期后才弄清楚,这是一个未记录的子类化问题ObservableObject
,如this SO answer所示。
这特别烦人,因为 Xcode 显然会提示您删除该类,因为父类提供了对 的继承ObservableObject
,所以在我看来一切都很好。
解决方法是,在子类中,self.objectWillChange.send()
通过willSet
相关@Published
变量或任何您需要的侦听器手动触发通用状态更改。
在我提供的示例ApiObject
中,问题中的基类保持不变。
虽然,CustomDataController
需要修改如下:
// DataController.swift
// This is a genericised example of the production code.
// These controllers build, manage and serve their resource data.
import Foundation
import Combine
class CustomDataController: ApiObject
{
@Published public var customData: [CustomDataStruct] = [] {
willSet {
// This is the generic state change fire that needs to be added.
self.objectWillChange.send()
}
}
public func fetch() -> Void
{
self.apiGetJson(
to: "custom-data-endpoint ",
decodeAs: [CustomDataStruct].self,
onDecode: { unwrappedJson in
self.customData = unwrappedJson
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
一旦我添加了手动发布,问题就解决了。
链接答案中的一个重要说明:不要重新声明objectWillChange
子类,因为这将再次导致状态无法正确更新。例如声明默认值
let objectWillChange = PassthroughSubject<Void, Never>()
Run Code Online (Sandbox Code Playgroud)
在子类上将再次中断状态更新,这需要保留在ObservableObject
直接扩展的父类上,无论是我的手动还是自动默认定义(输入或不输入并保留为继承声明)。
尽管您仍然可以根据PassthroughSubject
需要定义任意数量的自定义声明,而不会对子类产生问题,例如
// DataController.swift
// This is a genericised example of the production code.
// These controllers build, manage and serve their resource data.
import Foundation
import Combine
class CustomDataController: ApiObject
{
var customDataWillUpdate = PassthroughSubject<[CustomDataStruct], Never>()
@Published public var customData: [CustomDataStruct] = [] {
willSet {
// Custom state change handler.
self.customDataWillUpdate.send(newValue)
// This is the generic state change fire that needs to be added.
self.objectWillChange.send()
}
}
public func fetch() -> Void
{
self.apiGetJson(
to: "custom-data-endpoint ",
decodeAs: [CustomDataStruct].self,
onDecode: { unwrappedJson in
self.customData = unwrappedJson
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
只要
self.objectWillChange.send()
对遗体@Published
需要在子类的属性PassthroughSubject
不会在子类上重新声明默认声明它将正常工作并传播状态更改。
归档时间: |
|
查看次数: |
3130 次 |
最近记录: |