【问题标题】:View Update when Function Result changes | SwiftUI函数结果变化时查看更新 | SwiftUI
【发布时间】:2022-01-03 10:14:27
【问题描述】:

我遇到了一个问题。我有一个 SwiftUI 视图,其中有一个 ForEach(){} 循环。此循环中的每个对象都从外部函数中获取一些 Number,如下所示:

func returnRightNum(_ item: typeOfElements) -> Int {
        // Make some calculation
        var someExampleNum = 5
        return someExampleNum
    }

    var body: some View {
        ForEach(myArray){ element in
            Text("\(returnRightNum(element))")
        }
    }

到目前为止,一切都很好,现在我的问题是:returnRightNum 函数返回一个值,具体取决于其他一些值的状态。这意味着returnRightNum 的结果应该改变,只要这些值改变。但是这个函数只在视图渲染时被调用一次。让我给你看一些代码。

var otherValue1: Bool = false
    var otherValue2: Bool = false
    var otherValue3: Bool = false    

    func returnRightNum(_ item: typeOfElements) -> Int {
        // Make some calculation, depending on otherValue1, otherValue2 and otherValue3.

        var someExampleNum = 5

        // Change the Result
        if otherValue2 && otherValue3 {
            someExampleNum = 3
        } else if otherValue1 {
            someExampleNum = 2
        } else {
            someExampleNum = 1
        }

        return someExampleNum
    }

    var body: some View {
        ForEach(myArray){ element in
            Text("\(returnRightNum(element))")
        }
    }

我知道,您可以使用计算属性来解决这个问题,如下所示:

var computedValue: Int {
            // Make some calculation, depending on otherValue1, otherValue2 and otherValue3.
    
            var someExampleNum = 5
    
            // Change the Result
            if otherValue2 && otherValue3 {
                someExampleNum = 3
            } else if otherValue1 {
                someExampleNum = 2
            } else {
                someExampleNum = 1
            }
    
            return someExampleNum
        }

但这对我不起作用,因为someExampleNum 依赖于输入,并且您不能为计算属性提供特殊输入...

我需要一个函数,当它的值发生变化时,它会触发像 @State 这样的视图更新。

有什么方法可以实现吗,或者你有其他想法来解决这个问题吗?

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    如果对otherValue1otherValue2otherValue3 的更新意味着应该重新渲染您的视图,那么这些变量应该是@State@Binding 属性。如果值发生变化,这将触发重新渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 2021-09-20
      • 2018-07-22
      • 1970-01-01
      相关资源
      最近更新 更多