SwiftUI:工作表无法在第一次显示正确的值 [英] SwiftUI: Sheet cannot show correct values in first time

查看:75
本文介绍了SwiftUI:工作表无法在第一次显示正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SwiftUI中发现了奇怪的行为.

I found strange behavior in SwiftUI.

当我第一次点击列表列时,工作表显示空白文本.似乎第二次以后是正确的.

The sheet shows empty text when I tap a list column first time. It seems correct after second time.

你能帮我吗?

import SwiftUI

let fruits: [String] = [
    "Apple",
    "Banana",
    "Orange",
]

struct ContentView: View {
    @State var isShowintSheet = false
    @State var selected: String = ""
    var body: some View {
        NavigationView {
            List(fruits, id: \.self) { fruit in
                Button(action: {
                    selected = fruit
                    isShowintSheet = true
                }) {
                    Text(fruit)
                }
            }
        }
        .sheet(isPresented: $isShowintSheet, content: {
            Text(selected)
        })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

列表

第一次点击

第二次点击

推荐答案

请改用 .sheet(item:).这是固定代码.

Use .sheet(item:) instead. Here is fixed code.

已通过Xcode 12.1/iOS 14.1验证

Verified with Xcode 12.1 / iOS 14.1

struct ContentView: View {
    @State var selected: String?
    var body: some View {
        NavigationView {
            List(fruits, id: \.self) { fruit in
                Button(action: {
                    selected = fruit
                }) {
                    Text(fruit)
                }
            }
        }
        .sheet(item: $selected, content: { item in
            Text(item)
        })
    }
}

extension String: Identifiable {
    public var id: String { self }
}

这篇关于SwiftUI:工作表无法在第一次显示正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆