Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

ios - SwiftUI: Sheet cannot show correct values in first time

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.

Would you help me?

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()
    }
}

list

first tap

after second tap

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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 }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...