SWIFTUI: app buttons logic - change label in specific scenario - if-statement

My app has a number of mainButton created by a single struct. The data is passed to these buttons from an array. Then I have a Submit button.
I am trying to have the Submit button to change label to a arrow up icon only when: a given instance of mainButton has been pressed once already and changed its color and size already (this works), and Submit was pressed once already. Now the Submit button's icon changes to a refresh symbol (arrow up), until a diffrent instance of mainButton has been pressed (and this new button in turn has changed the color and size already as expected).
Basically a button representing a value is selected(tapped) and then its content submitted by pressing the Submit button, and if you submit the same button again the submitter is a refresher (arrow up icon) rather than a submitter (Submit label) as you have submitted that given query before; hence if you want to submit the same value again, the button is submit button is labeled as a refresher. The code below should make this clearer.
I am new to Swift/SwiftUI and trying to do this in a simple way as I want to understand it fully. Hence, if possible, I would rather use if conditions and variables rather than advanced methods.
Here is a simplified version of my code with only place holders in it:
//
// AddView.swift
// WriteOn
//
// Created by Maurizio Zappettini on 2/11/23.
//
import SwiftUI
struct AddView: View {
#State private var typeofMessageGeneric: String = ""
#State private var lastButtonTapped: String = ""
#State private var buttonCount: Int = 0
let buttonData = [
(mainButtonText: "A", mainButtonValue: "a"),
(mainButtonText: "B", mainButtonValue: "b"),
(mainButtonText: "C", mainButtonValue: "c"),
(mainButtonText: "D", mainButtonValue: "d"),
]
var body: some View {
ZStack { // Using ZStack for background gradient
Rectangle()
.frame(
minWidth: 0,
maxWidth: .infinity,
minHeight: 0,
maxHeight: .infinity,
alignment: .topLeading)
.foregroundColor(.clear)
.background(LinearGradient(colors: [.blue, .purple], startPoint: .top, endPoint: .bottom))
VStack { //Master VStack
VStack { //Headline
Text("Test View")
.font(.headline)
.padding()
}
GeometryReader { geometry in // Debug alignment
VStack(alignment: .center) { //TextBox
Rectangle()
.fill(Color.cyan)
.cornerRadius(20)
.frame(width: geometry.size.width * 0.8, height: 250, alignment: .center)
.overlay(
HStack(alignment: .top){
VStack {
Spacer()
}
ScrollView {
VStack(alignment: .center) {
Text("getResponsePlaceHolder")
.foregroundColor(.black)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
.layoutPriority(2)
}
}
VStack{
ShareLink(item: "nothing"){
Image(systemName: "square.and.arrow.up")
.resizable()
.scaledToFit()
.frame(width: 25, height: 25)
.foregroundColor(.black)
}
}
VStack{
Spacer()
}
}
.frame(height: geometry.size.height * 0.6) // find way to make it refer to actual box and not whole screen
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} //Vstack Top
} //Geo Reader
Spacer(minLength: 50
)
ScrollView{
VStack { //Buttons
ForEach(buttonData, id: \.mainButtonValue) { data in
mainButton(typeofMessageGeneric: self.$typeofMessageGeneric, lastButtonTapped: self.$lastButtonTapped, buttonCount: self.$buttonCount, mainButtonText: data.mainButtonText, mainButtonValue: data.mainButtonValue)
}
} //Button Vstack end
}
VStack{ //Footer
submitButton()
}
}
}
}
func submitButton() -> some View {
return Button(action: getResponse) {
if self.typeofMessageGeneric == self.lastButtonTapped && self.buttonCount == 0 {
Text("Submit")
.font(.system(size: 20))
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)
} else {
Image(systemName: "arrow.clockwise.circle")
.font(.system(size: 30))
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)
}
}
}
// Create main buttons
struct mainButton: View {
#Binding var typeofMessageGeneric: String // Bind the variable inside this struct with the same one inside the ContentView struct
#Binding var lastButtonTapped: String // Not currently used -- implement later if needed
#Binding var buttonCount:Int
var mainButtonText:String
var mainButtonValue:String
var body: some View {
Button(action: {
self.typeofMessageGeneric = mainButtonValue
self.lastButtonTapped = mainButtonValue
buttonCount = 0
if self.typeofMessageGeneric == mainButtonValue{
buttonCount = 1
} else {
buttonCount = 0
}
}) {
Text(mainButtonText)
Text(String(buttonCount)) // testing only
}
.font(.system(size: 20))
.foregroundColor(.white)
.padding()
.background(self.mainButtonValue == self.typeofMessageGeneric ? Color.teal : Color.purple)
.cornerRadius(10)
.scaleEffect(self.mainButtonValue == self.typeofMessageGeneric ? 1.12 : 1)
.animation(.easeOut, value: 2)
}
}
func getResponse() {
}
}
struct AddView_Previews: PreviewProvider {
static var previews: some View {
AddView()
}
}
EDIT:
Here is a better explanation of what the app does and what I am trying to achieve in terms of button logic.
What's on the screen when you start the app:
There is an empty text box.
There are 4 buttons (it will be more)
There is a Submit button at the bottom
What the app does:
The 4 main buttons are 4 different prompts. Each prompt/button is composed of a label and an associated value.
Tapping a button acts as a way to select that button's corresponding value.
Tapping the submit button will submit the value of the last selected main buttons to an external API. The latter will return some specific data that is visualized in the text box above (this part I left out as it is unrelated to my button label problem).
If the same prompt is submitted again the API will return different data (as there is a randomization mechanism). Hence, the user may want to submit again the same prompt they have submitted already.
How the buttons behave (practical example):
1- You tap button B
2- Button B changes the background color from purple to teal and becomes bigger.
3- You tap the "Submit" button.
4- The submit button changes its label from "Submit" to ARROW_UP.
5- The app submits value "b" to the API and this returns DATA_b_1.
6- DATA_b_1 is visualized in the text box.
7- Button B is still 'selected' (it is still teal and larger)
8- You tap ARROW_UP.
9- Value "b" is submitted again to the API and this now returns
DATA_b_2 (a different random instance of DATA_b).
10- DATA_b_2 is visualized in the text box.
11- You now tap button D.
12- Button D changes the background color from purple to teal and becomes bigger.
13- Button B reverts its color to purple and its size to smaller.
14- ARROW_UP button reverts its label to "Submit".
15- Back to point 3
Everything in the list above works as expected except the "Submit" to ARROW_UP and vice-versa label changes.

I hope I understood what you are trying to achieve, the. question is not very clear to me. What I got is:
Show the question and 4 possible answers to the user. Let the user select an answer. Submit button: disabled.
The user selects one answer; they can change their mind as much as they want until the answer is submitted. Submit button: enabled.
The user pressed "Submit": they can't press any other button, except for "Refresh". Submit button: "arrow up".
The user pressed "Refresh": go back to 1.
If that's the case, you just need to track two things:
what is the selected answer (when none is selected, nothing can be submitted)
when the answer was submitted - then, the only option is to refresh the question
By the way, your variable buttonCount is pointless: if you have only one variable for the whole view, all buttons will show the same number.
With a good set of ifs and elses, the "Submit" button can be disabled, enabled or show "arrow up", and perform the right action. Here's the code:
// Track which button was pressed - or none of them (starting case)
#State private var buttonPressed: String = ""
// Track if a choice was submitted - when submitted, the Submit button can only refresh
#State private var isWaitingToRefresh = false
// For testing only - tests the refresh
#State private var question = "0"
// (other code)
var body: some View {
// (other code)
Text("getResponsePlaceHolder \(question)")
// (other code)
ScrollView{
VStack { //Buttons
ForEach(buttonData, id: \.mainButtonValue) { data in
// Call a function, no need for binding vars
mainButton(mainButtonText: data.mainButtonText,
mainButtonValue: data.mainButtonValue)
}
} //Button Vstack end
}
submitButton()
}
}
}
func submitButton() -> some View {
Button {
// No action if no button was pressed
guard !buttonPressed.isEmpty else { return }
// Check if you need to refresh the question
if isWaitingToRefresh {
// If the view is waiting to refresh, then refresh the question
refresh()
isWaitingToRefresh = false
} else {
// If the view is not waiting to refresh, submit the user's choice
isWaitingToRefresh = true
getResponse()
}
} label: {
if !isWaitingToRefresh {
Text("Submit")
.font(.system(size: 20))
.foregroundColor(.white)
.padding()
// Gray-out the button if the user made no choice yet
.background(buttonPressed.isEmpty ? Color.secondary : Color.blue)
.cornerRadius(10)
} else {
Image(systemName: "arrow.clockwise.circle")
.font(.system(size: 30))
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)
}
}
// Disable the button if the user made no choice yet
.disabled(buttonPressed.isEmpty)
}
// Create main buttons
// Call a function, no need for binding vars:
// you can use the same variables of the view
func mainButton(mainButtonText: String,
mainButtonValue: String) -> some View {
Button {
// You just need to change the choice when a button is pressed,
// let the Submit button do the rest
buttonPressed = mainButtonValue
} label: {
Text(mainButtonText)
Text(String("same number for all buttons")) // testing only
}
.font(.system(size: 20))
.foregroundColor(.white)
.padding()
.background(mainButtonValue == buttonPressed ? Color.teal : Color.purple)
.cornerRadius(10)
.scaleEffect(mainButtonValue == buttonPressed ? 1.12 : 1)
.animation(.easeOut, value: 2)
// Do not let the user change the choice if it was already submitted
.disabled(isWaitingToRefresh)
}
// Remember to reset the user's choice (buttonPressed = "")
func refresh() {
buttonPressed = ""
question = String(Int.random(in: 1...100))
}

Related

How did Apple create the navigation view in this modal?

In iOS Settings > Music > Apple Music and Privacy, there is a modal that I've mostly successfully duplicated except in two ways (a brief demo of Apple's modal is here). First, I don't know how to duplicate the bullet points seen in the beginning of the text. Second, I don't know how to hide the nav bar title until scrolling past the logo and modal title. That behavior matches the .inline nav title style and suggests the logo and title are actually part of the nav bar title.
The answer here was really helpful in actually getting the nav bar to show up. I also tried using ToolbarItem and .principal from here to add an image to the toolbar, but that doesn't give the desired result. I tried adding padding because the image was squished into the nav bar but that didn't work. Lastly, I tried a VStack in the .principal placement to add the image and text below it, but that didn't work either.
Here's the code in the parent view:
struct ModalNavBar: View {
#State private var showApplePolicy = false
var body: some View {
Button() {
showApplePolicy = true
} label: {
Text("Apple Music and Privacy")
}.sheet(isPresented: $showApplePolicy, content: {
NavigationView {
TermsAndPrivacyView()
.navigationTitle("Apple Music & Privacy")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .principal) {
VStack {
Image("privacy")
.resizable()
.frame(width: 80, height: 65)
.padding()
.padding(.vertical, 20)
Text("Apple Music & Privacy")
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
self.showApplePolicy = false
}) {
Text("Done").bold()
}
}
}
}
})
}
}
and the modal view:
struct TermsAndPrivacyView: View {
var body: some View {
ScrollView {
VStack(alignment: .center, spacing: 20) {
Group {
Image("privacy")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 80, height: 65)
.padding()
.padding(.top, 20)
.padding(.bottom, 5)
Text("Apple Music & Privacy")
.font(.title).bold().padding(.top, -20)
VStack(alignment: .center) {
Text("Apple Music is designed to protect your information and enable you to choose what you share.")
}
}
}.padding(.horizontal, 30)
}
}
}
Any help with the nav bar would be appreciated.
Firstly, This question should have been broken up into multiple questions. Normally that would have gotten the question closed, but here people only downvoted this. Make sure to read the links that I put in my first comment for future questions. Your questions are:
How do I put place two texts or images next to each other and align them?
How do I hide and show the .navigationTitle when a certain view is fully hidden behind the navigation bar?
In answer to the first question, I used a mix of .firstTextBaseline alignment and an .alignmentGuide to put the text bullet in the correct spot. While I hardcoded these values, try to avoid it if things can change. In this case, the view is unchanging so it is acceptable.
As to the hiding and showing the title, I used a PreferenceKey to read the location of the bottom of the Text("Apple Music & Privacy") view in the ScrollView. When that hits zero, this view is behind the navigation bar. Then I simply set a #State variable to toggle when this happens, and use that to set the title.
You will also notice I pulled everything that was in your ModalNavBar out. In a case like this, everything should be contained in the view that the sheet is displaying. It works better, and encapsulates things so you could just drop a different view into the sheet and it still works fine.
Lastly, I have omitted a bunch of text views to keep the answer brief. Feel free to add them back in. When you see the ellipsis, that simply means omitted code.
struct ModalNavBar: View {
#State private var showApplePolicy = false
var body: some View {
Button() {
showApplePolicy = true
} label: {
Text("Apple Music & Privacy")
}.sheet(isPresented: $showApplePolicy, content: {
NavigationView {
TermsAndPrivacyView()
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
self.showApplePolicy = false
}) {
Text("Done").bold()
}
}
}
}
})
}
}
struct TermsAndPrivacyView: View {
#State var showTitle = false
var body: some View {
ScrollView {
VStack(alignment: .center, spacing: 20) {
Image(systemName: "person.3.fill")
.font(.system(size: 80))
Text("Apple Music & Privacy")
.font(.title).bold()
// The PreferenceKey reads where it is within the ScrollView. "Scroll" is a coordinate space name
// set on the ScrollView. .maxY is simply the value of the Y dimension at the bottom of that view
// within the coordinates of the ScrollView. When that hits zero, it is behind the navigation bar.
.background(
GeometryReader {
Color.clear.preference(key: TextLocationPrefKey.self,
value: $0.frame(in: .named("Scroll")).maxY)
}
)
Text("Apple Music is designed to protect your information and enable you to choose what you share.")
// Put the text bullet and text together in an HStack with a .firstTextBaseline alignement
HStack(alignment: .firstTextBaseline) {
Text(Image(systemName: "circle.fill"))
.font(.system(size: 4))
.opacity(0.5)
// The .alignmentGuide let's you tweak the actual alignment. In this case I moved it up by 2.
.alignmentGuide(.firstTextBaseline) { context in
context.height + 2
}
Text("Lorem ipsum dolor sit amet, praesent necessitatibus ei has, te sit hinc munere, ea vix fugit novum noluisse. Nulla graeci delicatissimi qui cu, nec doming iudicabit ex, indoctum partiendo an has. In qui sensibus dissentiunt, inani iudico accusamus ei eum. Suas vidit primis vel ad, meis ignota postea at pri, ei usu consul evertitur. Per vocent sadipscing et. Has debitis deterruisset ei, democritum scribentur te duo, purto accommodare id ius.")
}
...
}.padding(.horizontal, 30)
}
// This is a simple ternary condition. If showTitle is true the title is set to "Apple Music & Privacy" else ""
.navigationTitle(showTitle ? "Apple Music & Privacy" : "")
.navigationBarTitleDisplayMode(.inline)
// This is where the PreferenceKey value is compared to zero to set the showTitle variable.
.onPreferenceChange(TextLocationPrefKey.self) { textLocation in
withAnimation(.easeIn(duration: 0.15)) {
showTitle = !(textLocation > 0)
}
}
// This is where you select and name the view for the coordinate space
.coordinateSpace(name: "Scroll")
}
}
// This is how the preference key is set up.
fileprivate struct TextLocationPrefKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue = CGFloat.zero
static func reduce(value: inout Value, nextValue: () -> Value) {
// This adds or subtracts based on the change in the value as you scroll the view towards the navigation
// bar, nextValue() is negative, reducing value towards zero.
value += nextValue()
}
}

Radiobuttons in List swiftUI

Im displaying data from server and need to display the options in radiobuttons. But default none of the button should be selected. I was able to display radiobuttons. But when a particular button is clicked, only its image should be changed. Though with my code all the other button images too change. I have gone through some references SwiftUI - How to change the button's image on click?, but couldn't get it work. As am a newbie to SwiftUI, strucked here.
struct ListView: View {
#State var imageName: String = "radio-off"
var body: some View {
List(vwModel.OpnChoice.ItemList) { opn in
VStack(alignment:.leading) {
ForEach(opn.Choices.indices, id: \.self) { row in
Button(action: {
print("\(opn.Choices[row].ChoiceId)")
self.imageName = "radio-On"
}) {
Image(imageName)
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 30, height: 30)
}
Text(opn.Choices[row].ChoiceName)
}
}
}
}
}
As you are working with indices anyway, add a #Published property to your view model which contains the selected index.
Then set the index in the button action. The redraw of the view sets the button at the selected index to the on-state and the others to the off-state.
As I don't know your environment this is a simplified stand-alone view model and view with SF Symbols images
class VMModel : ObservableObject {
#Published var selectedOption = -1
var numberOfOptions = 5
}
struct ListView: View {
#StateObject private var vwModel = VMModel()
var body: some View {
VStack(alignment:.leading) {
ForEach(0..<vwModel.numberOfOptions, id: \.self) { opn in
Button(action: {
vwModel.selectedOption = opn
print("index \(opn) selected")
}) {
Image(systemName: opn == vwModel.selectedOption ? "largecircle.fill.circle" : "circle")
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 30, height: 30)
}
}
}
}
}
Update:
Meanwhile you can use a Picker with the .radioGroup modifier
enum Choice {
case one, two, three
}
struct ListView: View {
#State private var choice : Choice = .one
var body: some View {
Picker(selection: $choice, label: Text("Select an option:")) {
Text("One").tag(Choice.one)
Text("Two").tag(Choice.two)
Text("Three").tag(Choice.three)
}.pickerStyle(.radioGroup)
}
}
At the moment you are storing a single #State property "imageName" for the entire list. And then when any of the buttons in the list are tapped you are changing that single property. Which will affect all the buttons.
I'd suggest removing this property and putting something into the viewModel.
You appear to have a view model with an array called vwModel.opnChoice.itemList.
There are multiple ways of making this work. You could stop a boolean in the itemList to say whether each item is selected or not. But, as you want it to work like radio buttons what might be better is to have a property on the vwModel like selectedItem.
The button could then do...
vwModel.selectedItemId = opn.choices[row].choiceId
Then you button Label would be...
Image(vsModel.selectedItemId == opn.choices[row].choiceId ? "radio-on" : "radio-off")
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 30, height: 30)
This would allow you to toggle the button when it is tapped and should turn the other buttons off.

SwiftUI add border to onSelect horizontal Scrollview image

I tried to make a horizontal scrollview that contained a list of item. when I clicked any of the item, it will show a border(highlight) behind the item. When I press another item, the previous border disappear and the latest clicked item appear the border. It just looks like a selection horizontal scrollview. I have no idea about how to do so.
ScrollView(.horizontal, showsIndicators: false){
LazyHStack{
ForEach(self.staffs.indices, id: \.self){ staff in
VStack{
Image(staff.image)
.resizable()
.frame(width: 100, height: 100)
.clipShape(Circle())
}
.onTapGesture {
print(createBookingJSON.staffs[staff].staffID!)
}
}
}
}
Convert your VStack into a standalone view, then pass a Binding to it that can be read from the Parent View. Your new VStack standalone view needs an OnTapGesture or an Action through a button to toggle it's state. We will make your ForEach a "single selection" list as you request.
NEW View to use inside your ForEach:
struct ItemCell: View {
var item: Item
#Binding var selectedItem: Item?
var body: some View {
VStack{
Image(item.image)
.resizable()
.frame(width: 100, height: 100)
.border(Color.green, width: (item == selectedItem) ? 20 : 0)
}
.onTapGesture {
self.selectedItem = item
print(createBookingJSON.staffs[staff].staffID!)
}
}
}
Now in the view that contains your Foreach, add a State Var of selectedItem so you can read the Binding you created in your cells. And Replace your VStack with your new ItemCell:
struct YourParentView: View {
#State var selectedItem: Item? = nil
var body: some View {
ScrollView(.horizontal, showsIndicators: false){
LazyHStack{
ForEach(self.staffs.indices, id: \.self){ staff in
ItemCell(item: staff, selectedItem: self.$selectedItem)
}
}
}
}
}
Now when you click on the item, a border should appear. You may need to play with the border depending on your design, and the clipShape you have used of Circle(). Good Luck comrade.

Why tap Gesture of Button get triggered even out side of it's frame in SwiftUI?

I was testing accuracy of recognizing tap Gesture of a simple Button in SwiftUI, which I noticed it get activated even outside of its frame! I wanted be sure that I am not messing with label or other thing of Button, there for I build 2 different Buttons to find any improvement, but both of them get triggered in outside of given frame. I made a gif for showing issue.
gif:
code:
struct ContentView: View {
var body: some View {
Spacer()
Button("tap me!") {
print("you just tapped Button1!")
}.font(Font.largeTitle.bold()).background(Color.red)
Spacer()
Button(action: {
print("you just tapped Button2!")
}, label: {
Text("tap me!").font(Font.largeTitle.bold()).background(Color.red)
})
Spacer()
}
}
update:
some one said:
Do you see circle on click? - It is a size of active tap spot (kind of finger), and as you see, from your own demo, it overlaps red square - so gesture detected. That's it
I made another gif to show it is completely wrong to thinking like that, in this gif, even with overlaps tap get not registered!
I don't have an answer why this happens other than maybe there is some built-in functionality that increases the tappable area where possible for a better user experience? Anyway, if you put another tappable button behind it or next to it, you'll notice that this no longer happens and the tappable area is exactly where you'd expect it. Therefore, I wouldn't worry about it. But if you need to clip the tap area to the exact frame, you could add a clear background to the button and add a tap event that doesn't doesn't do anything, but takes priority on that location.
var body: some View {
VStack {
// Button behind button will take priority tap.
ZStack {
Button(action: {
print("tap 2")
}, label: {
Text("tap me!")
.padding()
.font(Font.largeTitle.bold())
.background(Color.green)
})
Button(action: {
print("tap 1")
}, label: {
Text("tap me!")
.font(Font.largeTitle.bold())
.background(Color.red)
})
}
// Clear background with "fake" tap event
Button(action: {
print("tap 3")
}, label: {
Text("tap me!")
.font(Font.largeTitle.bold())
.background(Color.red)
})
.padding()
.background(Color.black.opacity(0.001).onTapGesture {
//print("tap 4")
})
}
}
I think it's a built-in functionality to expand the tappable area:
Color.red
.frame(width: 30.0, height: 30.0)
.gesture(DragGesture(minimumDistance: 0).onEnded({ (value) in
// Tap with Apple Pencil: location is exactly the frame
// Tap with finger or an capacitance pen: the hit location is inaccurate
print(value.startLocation)
}))
Solution (Bug: If the view is inside a ScrollView, this will block scroll gesture):
let size = CGSize(width: 200.0, height: 200.0)
Color.red
.frame(width: size.width, height: size.height)
.gesture(DragGesture(minimumDistance: 0).onEnded({ (value) in
print(value.startLocation)
if value.startLocation.x >= 0 && value.startLocation.y >= 0 && value.startLocation.x <= size.width && value.startLocation.y <= size.height {
print("inside frame")
// action ...
} else {
print("outside frame")
}
}))

SwiftUI - How to initialize only one SectionView in ScrollView using onTapGesture

My problem is that when user presses on the item in my ScrollView all of the SectionView items changes. What I want to do is to change only one item. I'm trying to change item image when user taps on it and then when user taps on another item to bring back previous item image and change the current item image.
Take a look at my ScrollView:
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 15) {
ForEach(1..<41) { item in
GeometryReader { geometry in
SectionView(number: item, pressed: pressed, firstElement: (item == 1) ? true : false)
.rotation3DEffect(Angle(degrees:
Double(geometry.frame(in: .global).minX - 30) / -20
), axis: (x: 0, y: 10, z: 0))
.onTapGesture {
self.pressed.toggle()
SectionView(number: item, pressed: self.pressed, firstElement: (item == 1) ? true : false)
print("touched item \(item)")
}
})
}
}
}
Here's my SectionView:
struct SectionView: View {
var number: Int
var pressed: Bool
var firstElement: Bool
var body: some View {
ZStack(alignment: .bottom) {
Image(pressed ? "t1" : "t\(number)")
.resizable()
.frame(maxWidth: .infinity)
.frame(maxHeight: .infinity)
.aspectRatio(contentMode: .fill)
Spacer()
Text(firstElement ? "" : "Pride")
.font(.system(size: 12, weight: .black))
.foregroundColor(.white)
.frame(maxWidth: .infinity, alignment: .center)
.padding(.bottom, 15)
}
.frame(width: 60, height: 80)
//.background(section.image)
.cornerRadius(7)
//.shadow(color: section.image.opacity(0.15), radius: 8, x: 0, y: 10)
}
}
I tried putting your code into some kind of buildable state, but I couldn't get it to compile or run, so I may be completely misinterpreting what you are trying to do. However, it seems to me you are using pressed as if you are capturing the state at the time of the press on that particular SectionView. However, it would have to be a State var to compile, so it will update all of the views, which is what I believe you are seeing. I think what you need to do is change pressed to be an Int that keeps track of the SectionView that was pressed, and compare it to number which lets the particular SectionView keep track of its identity.
Also, I don't think you want the SectionView in the tap gesture. I think you just want to change the state of the pressed variable and let it work its way through the hierarchy.