Unsafe Pointer? - list

I am receiving this error message.
I am trying to make a subview that I can reuses to display a row in my app.
For some reason, it is pointing to the index variable that I am using to iterate over my enum in my List to display my data.
Why is this happening? I am not sure how to refer to this variable outside of the subview.
struct DisplayRow: View {
var name: String
var code: String
var value: Double
var counter: Int
var body: some View {
List(0..<counter, id: \.self) {index in
VStack {
HStack {
Text(name)
Text(code)
}
Text("$\(value)")
}
}
}
}
struct ContentView: View {
var body: some View {
List {
Section(header: Text("Wounds")) {
DisplayWoundRow()
}
Section(header: Text("Debride")) {
DisplayRow(name: debride.allCases[index].rawValue, code: debridecode.allCases[index].rawValue, value: debridevalue.allCases[index].rawValue, counter: debride.allCases.count)
}
}

You need ForEach for that, like
Section(header: Text("Debride")) {
ForEach(0..<debride.allCases.count, id: \.self) { index in // << here !!
DisplayRow(name: debride.allCases[index].rawValue, code: debridecode.allCases[index].rawValue, value: debridevalue.allCases[index].rawValue, counter: debride.allCases.count)
}
}
*I don't have all those types and cannot test, so typos or other errors are on you.

Related

Cannot convert value of type 'PuzzleView' to expected argument type 'Puzzle'

A week into learning SwiftUI, this is probably a simple error I'm making but can't figure it out… Trying to separate my views from model etc. However, when I call my view I get the error "Cannot convert value of type 'PuzzleView' to expected argument type 'Puzzle'".
My model is:
struct Puzzle : Codable, Identifiable {
var id: String
var region: String
var score: Int
var wordCount: Int
var pangramCount: Int
var foundPangrams: [String]
var solvedScore: Int
}
class PuzzleData : ObservableObject {
#Published var puzzles: [Puzzle]
init (puzzles: [Puzzle] = []) {
self.puzzles = puzzles
}
}
ContentView (no errors)
struct ContentView: View {
#StateObject var puzzleData : PuzzleData = PuzzleData(puzzles: getJson)
var body: some View {
NavigationView {
List {
ForEach (puzzleData.puzzles) { puzzle in
ListPuzzles(puzzle: puzzle)
}
}
.navigationBarTitle(Text("Puzzles"))
}
}
}
And the problem file with error:
struct PuzzleView: View {
let selectedPuzzle: Puzzle
var body: some View {
VStack {
Group {
Text(selectedPuzzle.id)
.font(.headline)
HStack {
DataRow(selectedPuzzle: Puzzle) //<<<<error here
}
Text(selectedPuzzle.region)
.font(.body)
}
}
}
}
The file it is linking to is:
struct DataRow: View {
var selectedPuzzle: Puzzle
var body: some View {
HStack {
Spacer()
Group {
VStack {
Text("Score")
Text("\(selectedPuzzle.solvedScore)/\\\(selectedPuzzle.score)")
}
VStack {
Text("Words")
Text("\(selectedPuzzle.foundWords.count - 1)/\\\(selectedPuzzle.wordCount)")
}
VStack {
Text("\((selectedPuzzle.pangramCount != 1) ? "Pangrams:" : "Pangram:")")
Text("\(selectedPuzzle.foundPangrams.count - 1)/\\\(selectedPuzzle.pangramCount)")
}
}
}
}
}
Will really appreciate any advise, thanks!

SwiftUI List messed up after delete action on iOS 15

It seems that there is a problem in SwiftUI with List and deleting items. The items in the list and data get out of sync.
This is the code sample that reproduces the problem:
import SwiftUI
struct ContentView: View {
#State var popupShown = false
var body: some View {
VStack {
Button("Show list") { popupShown.toggle() }
if popupShown {
MainListView()
}
}
.animation(.easeInOut, value: popupShown)
}
}
struct MainListView: View {
#State var texts = (0...10).map(String.init)
func delete(at positions: IndexSet) {
positions.forEach { texts.remove(at: $0) }
}
var body: some View {
List {
ForEach(texts, id: \.self) { Text($0) }
.onDelete { delete(at: $0) }
}
.frame(width: 300, height: 300)
}
}
If you perform a delete action on the first row and scroll to the last row, the data and list contents are not in sync anymore.
This is only happening when animation is attached to it. Removing .animation(.easeInOut, value: popupShown) workarounds the issue.
This code sample works as expected on iOS 14 and doesn't work on iOS 15.
Is there a workaround for this problem other then removing animation?
It isn't the animation(). The clue was seeing It appears that having the .animation outside of the conditional causes the problem. Moving it to the view itself corrected it to some extent. However, there is a problem with this ForEach construct: ForEach(texts, id: \.self). As soon as you start deleting elements of your array, the UI gets confused as to what to show where. You should ALWAYS use an Identifiable element in a ForEach. See the example code below:
struct ListDeleteView: View {
#State var popupShown = false
var body: some View {
VStack {
Button("Show list") { popupShown.toggle() }
if popupShown {
MainListView()
.animation(.easeInOut, value: popupShown)
}
}
}
}
struct MainListView: View {
#State var texts = (0...10).map({ TextMessage(message: $0.description) })
func delete(at positions: IndexSet) {
texts.remove(atOffsets: positions)
}
var body: some View {
List {
ForEach(texts) { Text($0.message) }
.onDelete { delete(at: $0) }
}
.frame(width: 300, height: 300)
}
}
struct TextMessage: Identifiable {
let id = UUID()
let message: String
}

Same ForEach loop twice in one SwiftUI View

When I use a ForEach loop over an array twice within a view, I get the following warning at runtime:
LazyVGridLayout: the ID 84308994-9D16-48D2-975E-DC40C5F9EFFF is used by multiple child views, this will give undefined results!
The reason for this is clear so far, but what is the smartest way to work around this problem?
The following sample code illustrates the problem:
import SwiftUI
// MARK: - Model
class Data: ObservableObject
{
#Published var items: [Item] = [Item(), Item(), Item()]
}
struct Item: Identifiable
{
let id = UUID()
var name: String = ""
var description: String = ""
}
// MARK: - View
struct MainView: View {
#StateObject var data: Data
private var gridItems: [GridItem] { Array(repeating: GridItem(), count: data.items.count) }
var body: some View {
LazyVGrid(columns: gridItems, alignment: .leading, spacing: 2) {
ForEach(data.items) { item in
Text(item.name)
}
ForEach(data.items) { item in
Text(item.description)
}
}
}
}
// MARK: - App
#main
struct SwiftUI_TestApp: App {
var body: some Scene {
WindowGroup {
MainView(data: Data())
}
}
}
I could possibly divide the view into several SubViews.
Are there any other options?
Edit:
This is the body of the real app:
var body: some View {
VStack {
LazyVGrid(columns: columns, alignment: .leading, spacing: 2) {
Text("")
ForEach($runde.players) { $player in
PlayerHeader(player: $player)
}
ForEach(Score.Index.allCases) { index in
Text(index.localizedName)
ForEach(runde.players) { player in
Cell(player: player, active: player == runde.activePlayer, index: index)
}
}
Text ("")
ForEach(runde.players) { player in
PlaceView(player: player)
}
}
.padding()
}
}
If you really need that kind of grid filling, then it is possible just to use different identifiers for those ForEach containers, like
LazyVGrid(columns: gridItems, alignment: .leading, spacing: 2) {
ForEach(data.items) { item in
Text(item.name).id("\(item.id)-1") // << here !!
}
ForEach(data.items) { item in
Text(item.description).id("\(item.id)-2") // << here !!
}
}
Tested with Xcode 13beta / iOS 15
While adding identifiers within the ForEach loop sometimes works, I found that accessing the indexes from the loop with indices worked in other cases:
ForEach(items.indices, id: \.self) { i in
Text(items[i])
}

Passing steper value to another View - SwiftUI

I have very simple "app" in SwiftUI
How i can passing stepper value from list to struct SumOfValue or to ContentView ? But i want passing sum of stepper value in case from image will be 8.
struct ContentView: View {
var body: some View {
VStack{
List{
ProductList()
ProductList()
}
Spacer()
Text("Sum of stepper value: ?????")
.padding(.bottom, 50
)
SumOfValue()
}
}
}
struct ProductList:View {
#State var stepperValueTest: Int = 0
var body: some View {
HStack {
Stepper("Value: \(stepperValueTest)", value: $stepperValueTest)
}
}
}
struct SumOfValue: View {
var body: some View {
Text("or here sum of value: ????? ")
.foregroundColor(Color.red)
}
}
I try use #Binding but didn`t work.
There are multiple approaches here, and it's ultimately a question of data organization.
One way to think about is that there is an array of values that a parent - ContentView in your case - "owns", and each child updates their allotted value in that array using a binding. This way, the parent can easily calculate the sum of these values since it has the entire array.
struct ContentView: View {
#State var values = [0,0,0]
var body: some View {
VStack {
List {
ProductList(stepperValueTest: $values[0])
ProductList(stepperValueTest: $values[1])
ProductList(stepperValueTest: $values[2])
}
Text("Sum: \(sum)")
}
}
var sum: Int { values.reduce(0, +) }
}
struct ProductList:View {
#Binding var stepperValueTest: Int // change to Binding
var body: some View {
HStack {
Stepper("Value: \(stepperValueTest)", value: $stepperValueTest)
}
}
}
The #State goes in the parent (ContentView), and the #Binding goes in the child (ProductList and SumOfValue).
Try this:
struct ContentView: View {
/// States here!
#State var firstStepperValue: Int = 0
#State var secondStepperValue: Int = 0
var body: some View {
VStack{
List{
/// pass it in here!
ProductList(stepperValueTest: $firstStepperValue)
ProductList(stepperValueTest: $secondStepperValue)
}
Spacer()
/// add the values here
Text("Sum of stepper value: \(firstStepperValue + secondStepperValue)")
.padding(.bottom, 50
)
/// you can also pass it in here
SumOfValue(first: $firstStepperValue, second: $secondStepperValue)
.padding(.bottom, 100)
}
}
}
struct ProductList:View {
/// Binding here!
#Binding var stepperValueTest: Int
var body: some View {
HStack {
Stepper("Value: \(stepperValueTest)", value: $stepperValueTest)
}
}
}
struct SumOfValue: View {
#Binding var first: Int
#Binding var second: Int
var body: some View {
Text("or here sum of value: \(first + second) ")
.foregroundColor(Color.red)
}
}
Result:

Conditionally Text in SwiftUI depending on Array value

I want make placeholder custom style so i try to use the method of Mojtaba Hosseini in SwiftUI. How to change the placeholder color of the TextField?
if text.isEmpty {
Text("Placeholder")
.foregroundColor(.red)
}
but in my case, I use a foreach with a Array for make a list of Textfield and Display or not the Text for simulate the custom placeholder.
ForEach(self.ListeEquip.indices, id: \.self) { item in
ForEach(self.ListeJoueurs[item].indices, id: \.self){idx in
// if self.ListeJoueurs[O][O] work
if self.ListeJoueurs[item][index].isEmpty {
Text("Placeholder")
.foregroundColor(.red)
}
}
}
How I can use dynamic conditional with a foreach ?
Now I have a another problem :
i have this code :
struct EquipView: View {
#State var ListeJoueurs = [
["saoul", "Remi"],
["Paul", "Kevin"]
]
#State var ListeEquip:[String] = [
"Rocket", "sayans"
]
var body: some View {
VStack { // Added this
ForEach(self.ListeEquip.indices) { item in
BulleEquip(EquipName: item, ListeJoueurs: self.$ListeJoueurs, ListeEquip: self.$ListeEquip)
}
}
}
}
struct BulleEquip: View {
var EquipName = 0
#Binding var ListeJoueurs :[[String]]
#Binding var ListeEquip :[String]
var body: some View {
VStack{
VStack{
Text("Équipe \(EquipName+1)")
}
VStack { // Added this
ForEach(self.ListeJoueurs[EquipName].indices) { index in
ListeJoueurView(EquipNamed: self.EquipName, JoueurIndex: index, ListeJoueurs: self.$ListeJoueurs, ListeEquip: self.$ListeEquip)
}
HStack{
Button(action: {
self.ListeJoueurs[self.EquipName].append("") //problem here
}){
Text("button")
}
}
}
}
}
}
struct ListeJoueurView: View {
var EquipNamed = 0
var JoueurIndex = 0
#Binding var ListeJoueurs :[[String]]
#Binding var ListeEquip :[String]
var body: some View {
HStack{
Text("Joueur \(JoueurIndex+1)")
}
}
}
I can run the App but I have this error in console when I click the button :
ForEach, Int, ListeJoueurView> count (3) != its initial count (2). ForEach(_:content:) should only be used for constant data. Instead conform data to Identifiable or use ForEach(_:id:content:) and provide an explicit id!
Can someone enlighten me?
TL;DR
You need a VStack, HStack, List, etc outside each ForEach.
Updated
For the second part of your question, you need to change your ForEach to include the id parameter:
ForEach(self.ListeJoueurs[EquipName].indices, id: \.self)
If the data is not constant and the number of elements may change, you need to include the id: \.self so SwiftUI knows where to insert the new views.
Example
Here's some example code that demonstrates a working nested ForEach. I made up a data model that matches how you were trying to call it.
struct ContentView: View {
// You can ignore these, since you have your own data model
var ListeEquip: [Int] = Array(1...3)
var ListeJoueurs: [[String]] = []
// Just some random data strings, some of which are empty
init() {
ListeJoueurs = (1...4).map { _ in (1...4).map { _ in Bool.random() ? "Text" : "" } }
}
var body: some View {
VStack { // Added this
ForEach(self.ListeEquip.indices, id: \.self) { item in
VStack { // Added this
ForEach(self.ListeJoueurs[item].indices, id: \.self) { index in
if self.ListeJoueurs[item][index].isEmpty { // If string is blank
Text("Placeholder")
.foregroundColor(.red)
} else { // If string is not blank
Text(self.ListeJoueurs[item][index])
}
}
}.border(Color.black)
}
}
}
}
Explanation
Here's what Apple's documentation says about ForEach:
A structure that computes views on demand from an underlying collection of of [sic] identified data.
So something like
ForEach(0..2, id: \.self) { number in
Text(number.description)
}
is really just shorthand for
Text("0")
Text("1")
Text("2")
So your ForEach is making a bunch of views, but this syntax for declaring views is only valid inside a View like VStack, HStack, List, Group, etc. The technical reason is because these views have an init that looks like
init(..., #ViewBuilder content: () -> Content)
and that #ViewBuilder does some magic that allows this unique syntax.