SwiftUI |从另一个SwiftUI视图访问PickerView选择

时间:2020-05-09 15:14:45

标签: ios swiftui xcode11.4 pickerview

我厌倦了基于user3441734 solution为动态选择器构建多组件选择器。该选择器位于其自己的.swift文件中。我不知道如何将所选内容保存到变量中以再次从另一个视图访问它。

到目前为止,这是我的代码。我在下面用?及其错误消息标记了错误的解决方案。

from PIL import Image

# load images
image = Image.open("image.png")
mask = Image.open("mask.png")

# stretch mask to fit image
mask = mask.resize(image.size)

# get the color of a pixel in the middle of the image to use as mask color
color = image.getpixel((500, 500))

# colorize the greyscale mask to that color, with the "blackness" of each pixel becoming the alpha channel
greyscale_to_color_with_alpha(mask, color)

# apply mask on top of image
image.paste(mask)

def greyscale_to_color_with_alpha(image, color):
    raise NotImplementedError

?类型'()'不符合'视图';只有struct / enum / class类型可以符合协议

1 个答案:

答案 0 :(得分:0)

不需要其他选择,因为选择已存储在模型中,所以

1)删除这些行

@State var selection: String = ""

// Save selection to variable ?
selection = "\(self.model.manufacturerNames[model.selectedManufacturer])-\(self.model.stockNames[model.selectedStock])"

2)不要创建内联模型,只需声明它可以通过构造函数进行注入

struct DynamicPicker: View {
    @ObservedObject var model: Model  // << here !!

3)对DynamicPicker使用与其他从属视图相同的模型,让我们假设它被称为ManufacturerView(已声明与上面相同的观察模型)。并且有一些根视图同时保留了两者,因此可能是

struct RootView: View {
    let model = Model() // << create it here

    var body: some View {
      VStack {
        DynamicPicker(model: self.model)
        ManufacturerView(model: self.model)
      }
    }
}

因此,当在DynamicPicker中更新选择内容时,ManufacturerView将自动更新为相应的选择内容,导致使用相同的数据源。