4

I have a list that displays 1, 2, and 3. When the text is tapped the app opens a sheet with the number tapped. However, if I tap the text in the second or third row, the number displayed in the sheet is still 1. What am I doing wrong?

import SwiftUI

struct ContentView: View {
    
    var numbers = [1, 2, 3]
    @State private var shouldPresentSheet = false
    
    var body: some View {
        List(self.numbers, id: \.self) { number in
            Text("number: \(number)").sheet(isPresented: self.$shouldPresentSheet) {
                Text("This is sheet number \(number)")
            }.onTapGesture {
                self.shouldPresentSheet.toggle()
            }
        }
    }
}
2
  • 2
    Consider this solution stackoverflow.com/a/63089069/12299030 - you have same problem. Commented Aug 15, 2020 at 13:38
  • @Asperi I completely forgot about extending Int, thanks. Commented Aug 15, 2020 at 13:59

1 Answer 1

4

You need to create one sheet instead of multiple sheets.

If you want to use .sheet(isPresented:content:) you can do the following:

struct ContentView: View {
    var numbers = [1, 2, 3]
    @State private var selectedNumber: Int?

    var body: some View {
        List(numbers, id: \.self) { number in
            Text("number: \(number)")
                .onTapGesture {
                    self.selectedNumber = number
                }
        }
        .sheet(isPresented: binding) {
            Text("This is a sheet number \(self.selectedNumber ?? 0)")
        }
    }

    var binding: Binding<Bool> {
        .init(
            get: { self.selectedNumber != nil },
            set: { _ in }
        )
    }
}

Alternatively you can use .sheet(item:content:):

struct Model: Identifiable {
    let id: Int
}

struct ContentView: View {
    var numbers = [1, 2, 3].map(Model.init)
    @State private var selectedNumber: Model?

    var body: some View {
        List(numbers, id: \.id) { number in
            Text("number: \(number.id)")
                .onTapGesture {
                    self.selectedNumber = number
                }
        }
        .sheet(item: $selectedNumber) { item in
            Text("This is a sheet number \(item.id)")
        }
    }
}

EDIT

If you decide to use .sheet(item:content:) you can add an extension to Int (instead of creating a custom struct conforming to Identifiable):

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

as proposed in Asperi's answer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.