SwiftUI图像不会更新

时间:2019-11-23 20:14:31

标签: ios swift xcode image swiftui

我真是新手。我究竟做错了什么?为什么按时图像没有更新?我找不到有关状态侦听器的任何信息。

这是捆绑两个视图的视图:

function getNthElementOfProperty(obj, key, n) {
    if(obj[key] === undefined){
      return undefined
    } else if(Array.isArray(obj[key]) === false){
      return undefined
    } else if(obj[key].length === 0){
      return undefined
    }
    for(var i = 0; i < obj[key].length; i++){
        if(i === n){
            return obj[key][i]
        }
    }
    return undefined;
  };

这是定义图像的视图:

import SwiftUI

struct FoodContentView: View {
    var body: some View {
        VStack {
            imageView.gesture(tap)
            FoodContentTextView().position(x: bodyWidth/3, y: bodyHeight/2)
        }
    }
}

var imageView = FoodContentImageView(selectedImage: "CheeseBurger")

let tap = TapGesture()
.onEnded { _ in
    if imageView.imageSelected == "Burger" {
        imageView.imageSelected = "CheeseBurger"
        print(imageView.imageSelected)
    } else {
        imageView.imageSelected = "Burger"
        print(imageView.imageSelected)
    }
}

1 个答案:

答案 0 :(得分:1)

您不必要地使其变得非常复杂。 FoodContentImageView只需要知道图像的名称:

struct FoodContentImageView: View {

    var imageName: String

    var body: some View {
        Image(imageName).resizable().frame(width: 200, height: 200, alignment: .center).scaledToFit()
    }
}

您只需要输入名称即可。如果将其存储为@State,它将在发生任何更改时自动更新:

struct ContentView: View {

    @State var text = "CheeseBurger"

    var body: some View {
        VStack {
            FoodContentImageView(imageName: text)
                .onTapGesture {
                    if self.text == "Burger" {
                        self.text = "CheeseBurger"
                    } else {
                        self.text = "Burger"
                    }
            }
        }
    }
}

并且根本不需要引用imageViewtapGesture