Skip to content

Instantly share code, notes, and snippets.

@CodeSlicing
Created May 24, 2021 11:58
Show Gist options
  • Save CodeSlicing/f340c215629abdef466bd9507fc9930a to your computer and use it in GitHub Desktop.
Save CodeSlicing/f340c215629abdef466bd9507fc9930a to your computer and use it in GitHub Desktop.
Demo of problem when using index to select an entry to display in a sheet/popup
//
// SheetWithIndexProblemDemo.swift.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Created by Adam Fordyce on 24/05/2021.
// Copyright © 2021 Adam Fordyce. All rights reserved.
//
import SwiftUI
private let defaultUsers: [String] = {
var users = [String]()
for userIndex in 0..<10 {
users.append("User \(userIndex)")
}
return users
}()
struct SheetWithIndexProblemDemo: View {
fileprivate var users = defaultUsers
@State private var selectedUserIndex = 0
@State private var showingUserDetails = false
var body: some View {
VStack {
ForEach(0..<users.count, id: \.self) { index in
Text(self.users[index])
.font(.title)
.onTapGesture {
self.selectedUserIndex = index
self.showingUserDetails = true
}
}
}
.sheet(isPresented: $showingUserDetails) {
Text(self.users[self.selectedUserIndex])
.font(.title)
}
}
}
struct EditingUserProblemWithIndex_Previews: PreviewProvider {
struct EditingUserProblemWithIndex_Harness: View {
var body: some View {
SheetWithIndexProblemDemo()
}
}
static var previews: some View {
EditingUserProblemWithIndex_Harness()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment