本文介绍了SwiftUI @State和.sheet()iOS13与iOS14的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我在这里遇到问题,在ios13或ios14上运行时,我的.sheet()视图之间没有一致的行为

Hello I am running into a problem here and I do not have a consistent behavior between my .sheet() view when running on ios13 or ios14

我有这样的看法:

@State private var label: String = ""
@State private var sheetDisplayed = false
///Some code
var body: some View {
   VStack {
      Button(action: {
         self.label = "A label"
         self.isDisplayed = true
      }) {
           Text("test")
       }
   }.sheet(isPresented: $sheetDisplayed, onDismiss: {
        self.label = ""
    }) {
        Text(self.label)
       }
 }

在ios 13上,此工作如预期的btn一样,单击->设置标签->电话单->显示标签"在文本"视图中.

On ios 13 this work as expected btn click -> set label -> call sheet -> display "A label" in a Text view.

在ios14上,我在工作表关闭时在self.label中有一个空字符串,因此它不显示任何内容.

On ios14 I got an empty string in self.label when in sheet closure, hence it does not display anything.

我错过了什么吗?是iOS 14的错误,还是我在ios13上出错了,并且已得到纠正.

Did I missed something ? Is it an iOS 14 bug or did I had it wrong on ios13 and that got corrected.

PS:我还简化了闭包中传递的其他几个变量.

PS: I have a couple of other variables that are passed in the closure I simplified it.

推荐答案

您的代码具有视图更新/创建顺序的期望,但总的来说它是未定义的(可能在iOS 14中已更改).

Your code have expectation of view update/creation order, but in general it is undefined (and probably changed in iOS 14).

有一种明确的方式可以在工作表内部传递信息-使用不同的工作表创建者,即.sheet(item:...

There is explicit way to pass information inside sheet - use different sheet creator, ie. .sheet(item:...

这是工作可靠的例子.经过Xcode 12/iOS 14的测试

Here is working reliable example. Tested with Xcode 12 / iOS 14

struct ContentView: View {
    @State private var item: Item?

    struct Item: Identifiable {
        let id = UUID()
        var label: String = ""
    }

    var body: some View {
        VStack {
            Button(action: {
                self.item = Item(label: "A label")
            }) {
                Text("test")
            }
        }.sheet(item: $item, onDismiss: {
            self.item = nil
        }) {
            Text($0.label)
        }
    }
}

这篇关于SwiftUI @State和.sheet()iOS13与iOS14的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 02:56