ForEach view can't apply the view modifier to selected view - swiftui

I have a simple horizontal list view that displays the list of colours and the problem is that I don't know how to apply border to only one selected view, for now it's adding the white border to all views in the list on didTap, please help if you know how to achieve it, thanks 🙌
Here's the code:
struct Colour: Identifiable {
var id: Int
var color: Color
}
struct ContentView: View {
#State private var didTap = false
#State private var colors: [Colour] = [
Colour(id: 1, color: .black),
Colour(id: 2, color: .yellow),
Colour(id: 3, color: .orange),
Colour(id: 4, color: .green),
Colour(id: 5, color: .red),
Colour(id: 6, color: .blue),
Colour(id: 7, color: .pink),
Colour(id: 8, color: .purple),
]
var body: some View {
ZStack {
Color.gray.opacity(0.2)
.ignoresSafeArea()
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 4) {
ForEach(colors) { color in
Rectangle()
.fill(color.color)
.frame(width: 100, height: 150)
.overlay(
Rectangle()
.stroke(didTap ? Color.white : .clear, lineWidth: 5)
.animation(.spring())
)
.padding(5)
.onTapGesture {
didTap.toggle()
print(color.id)
}
}
}
.padding(.leading, 8)
}
}
}
}

You need to store id of selected color instead of bool.
Here is simple demo (deselect on tap on same element is your excise). Tested with Xcode 12.5 / iOS 14.5
struct ContentView: View {
#State private var selected = -1 // << here !!
#State private var colors: [Colour] = [
Colour(id: 1, color: .black),
Colour(id: 2, color: .yellow),
Colour(id: 3, color: .orange),
Colour(id: 4, color: .green),
Colour(id: 5, color: .red),
Colour(id: 6, color: .blue),
Colour(id: 7, color: .pink),
Colour(id: 8, color: .purple),
]
var body: some View {
ZStack {
Color.gray.opacity(0.2)
.ignoresSafeArea()
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 4) {
ForEach(colors) { color in
Rectangle()
.fill(color.color)
.frame(width: 100, height: 150)
.overlay(
Rectangle()
.stroke(selected == color.id ? Color.white : .clear, lineWidth: 5)
.animation(.spring())
)
.padding(5)
.onTapGesture {
selected = color.id // << here !!
print(color.id)
}
}
}
.padding(.leading, 8)
}
}
}
}

Related

How can I change button status in SwiftUI?

I am trying to change the color programmatically of some buttons in SwiftUI.
The buttons are stored in a LazyVGrid. Each button is built via another view (ButtonCell).
I'm using a #State in the ButtonCell view to check the button state.
If I click on the single button, his own state changes correctly, just modifying the #State var of the ButtonCell view. If I try to do the same from the ContentView nothing is happening.
This is my whole ContentView (and ButtonCell) view struct:
struct ContentView: View {
private var gridItemLayout = [GridItem(.adaptive(minimum: 30))]
var body: some View {
let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
ScrollView {
LazyVGrid(columns: columns, spacing: 0) {
ForEach(0..<10) { number in
ButtonCell(value: number + 1)
}
}
}
Button(action: {
ButtonCell(value: 0, isEnabled: true)
ButtonCell(value: 1, isEnabled: true)
ButtonCell(value: 1, isEnabled: true)
}){
Rectangle()
.frame(width: 200, height: 50)
.cornerRadius(10)
.shadow(color: .black, radius: 3, x: 1, y: 1)
.padding()
.overlay(
Text("Change isEnabled state").foregroundColor(.white)
)
}
}
struct ButtonCell: View {
var value: Int
#State var isEnabled:Bool = false
var body: some View {
Button(action: {
print (value)
print (isEnabled)
isEnabled = true
}) {
Rectangle()
.foregroundColor(isEnabled ? Color.red : Color.yellow)
.frame(width: 50, height: 50)
.cornerRadius(10)
.shadow(color: .black, radius: 3, x: 1, y: 1)
.padding()
.overlay(
Text("\(value)").foregroundColor(.white)
)
}
}
}
}
How I may change the color of a button in the LazyVGrid by clicking the "Change isEnabled state" button?
You need a different approach here. Currently you try to change the State of ButtonCell from the outside. State variables should always be private and therefore should not be changed from outside. You should swap the state and parameters of ButtonCell into a ViewModel. The ViewModels then are stored in the parent View (ContentView) and then you can change the ViewModels and the child views automatically update. Here is a example for a ViewModel:
final class ButtonCellViewModel: ObservableObject {
#Published var isEnabled: Bool = false
let value: Int
init(value: Int) {
self.value = value
}
}
Then store the ViewModels in the ContentView:
struct ContentView: View {
let buttonViewModels = [ButtonCellViewModel(value: 0), ButtonCellViewModel(value: 1), ButtonCellViewModel(value: 2)]
private var gridItemLayout = [GridItem(.adaptive(minimum: 30))]
var body: some View {
let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
ScrollView {
LazyVGrid(columns: columns, spacing: 0) {
ForEach(0..<3) { index in
ButtonCell(viewModel: buttonViewModels[index])
}
}
}
Button(action: {
buttonViewModels[0].isEnabled.toggle()
}){
Rectangle()
.frame(width: 200, height: 50)
.cornerRadius(10)
.shadow(color: .black, radius: 3, x: 1, y: 1)
.padding()
.overlay(
Text("Change isEnabled state").foregroundColor(.white)
)
}
}
}
And implement the ObservedObject approach in ButtonCell.
struct ButtonCell: View {
#ObservedObject var viewModel: ButtonCellViewModel
var body: some View {
Button(action: {
print (viewModel.value)
print (viewModel.isEnabled)
viewModel.isEnabled = true
}) {
Rectangle()
.foregroundColor(viewModel.isEnabled ? Color.red : Color.yellow)
.frame(width: 50, height: 50)
.cornerRadius(10)
.shadow(color: .black, radius: 3, x: 1, y: 1)
.padding()
.overlay(
Text("\(viewModel.value)").foregroundColor(.white)
)
}
}
}

iOS 15.3 has broken SwiftUI layout

I just upgraded my phone from 15.x (I think 15.2) to 15.3, and my SwiftUI layout is broken, seems to be a List border issue.
Here is the code, followed by a screen shot of normal behavior (13.x to 15.x) and then what I see in 15.3
struct SessionView: View {
var title: String
var panel: Int
var index: Int
var range: [Int] = [0,2,3,4]
#EnvironmentObject var state: MainViewModel
#EnvironmentObject var content: ContentViewModel
#ViewBuilder
var body: some View {
VStack() {
// -- Header
HStack() {
Text(" ")
Image(self.state.panelIcon(panel: panel)).resizable().frame(width: 12.0, height: 12.0)
Text(title)
Spacer()
}.padding(EdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0))
.background(Color(red: 0.9, green: 0.9, blue: 0.9))
.onTapGesture {
showDetailDialog()
}
// -- Rows
List {
ForEach(0..<5) { i in
if i != 1 { // Skip IP address
HStack(alignment: /*#START_MENU_TOKEN#*/.center/*#END_MENU_TOKEN#*/, spacing: -4, content: {
Text("\(state.keyValues[i+index]!.key)").frame(minWidth: 120, maxHeight: 20, alignment: .leading)
.font(Font.system(size: 15, design: .default)).padding(0)
Text("\(state.keyValues[i+index]!.value)").frame(maxHeight: 20, alignment: .leading)
.font(Font.system(size: 15, design: .default)).padding(0)
}).frame(height: 10)
}
}
}.environment(\.defaultMinListRowHeight, 10)
.frame(height: 4*20+20)
.listStyle(DefaultListStyle()).environment(\.defaultMinListRowHeight, 8).onAppear {
UITableView.appearance().isScrollEnabled = false
}.layoutPriority(1)
}.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color(red: 0.8, green: 0.8, blue: 0.8), lineWidth: 1.25)
).background(Color.white)
}
.
.
.
}
I had this problem too. However, it is not a border issue. When you updated your iPhone, the default list style for SwiftUI changed. The old default style is now called PlainListStyle(). Use that instead to get the old look back.
List {
}.listStyle(PlainListStyle())

SwiftUI NavigationItem dynamic data sending incorrect parameter

I have what I thought was a simple task, but it appears otherwise. As part of my code, I am simply displaying some circles and when the user clicks on one, it will navigate to a new view depending on which circle was pressed.
If I hard code the views in the NavigationLink, it works fine, but I want to use a dynamic array. In the following code, it doesn't matter which circle is pressed, it will always display the id of the last item in the array; ie it passes the last defined dot.destinationId to the Game view
struct Dot: Identifiable {
let id = UUID()
let x: CGFloat
let y: CGFloat
let color: Color
let radius: CGFloat
let destinationId: Int
}
struct ContentView: View {
var dots = [
Dot(x:10.0,y:10.0, color: Color.green, radius: 12, destinationId: 1),
Dot(x:110.0,y:10.0, color: Color.green, radius: 12, destinationId: 2),
Dot(x:110.0,y:110.0, color: Color.blue, radius: 12, destinationId: 3),
Dot(x:210.0,y:110.0, color: Color.blue, radius: 12, destinationId: 4),
Dot(x:310.0,y:110.0, color: Color.red, radius: 14, destinationId: 5),
Dot(x:210.0,y:210.0, color: Color.blue, radius: 12, destinationId: 6)]
var lineWidth: CGFloat = 1
var body: some View {
NavigationView {
ZStack
Group {
ForEach(dots){ dot in
NavigationLink(destination: Game(id: dot.destinationId))
{
Circle()
.fill(dot.color)
.frame(width: dot.radius, height: dot.radius)
.position(x:dot.x, y: dot.y )
}
}
}
.frame(width: .infinity, height: .infinity, alignment: .center )
}
.navigationBarTitle("")
.navigationBarTitleDisplayMode(.inline)
}
}
struct Game: View {
var id: Int
var body: some View {
Text("\(id)")
}
}
I tried to send the actual view as i want to show different views and used AnyView, but the same occurred It was always causing the last defined view to be navigated to.
I'm really not sure what I a doing wrong, any pointers would be greatly appreciated
While it might seem that you're clicking on different dots, the reality is that you have a ZStack with overlapping views and you're always clicking on the top-most view. You can see when you tap that the dot with ID 6 is always the one actually getting pressed (notice its opacity changes when you click).
To fix this, move your frame and position modifiers outside of the NavigationLink so that they affect the link and the circle contained in it, instead of just the inner view.
Also, I modified your last frame since there were warnings about an invalid frame size (note the different between width/maxWidth and height/maxHeight when specifying .infinite).
struct ContentView: View {
var dots = [
Dot(x:10.0,y:10.0, color: Color.green, radius: 12, destinationId: 1),
Dot(x:110.0,y:10.0, color: Color.green, radius: 12, destinationId: 2),
Dot(x:110.0,y:110.0, color: Color.blue, radius: 12, destinationId: 3),
Dot(x:210.0,y:110.0, color: Color.blue, radius: 12, destinationId: 4),
Dot(x:310.0,y:110.0, color: Color.red, radius: 14, destinationId: 5),
Dot(x:210.0,y:210.0, color: Color.blue, radius: 12, destinationId: 6)]
var lineWidth: CGFloat = 1
var body: some View {
NavigationView {
ZStack {
Group {
ForEach(dots){ dot in
NavigationLink(destination: Game(id: dot.destinationId))
{
Circle()
.fill(dot.color)
}
.frame(width: dot.radius, height: dot.radius) //<-- Here
.position(x:dot.x, y: dot.y ) //<-- Here
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center )
}
.navigationBarTitle("")
.navigationBarTitleDisplayMode(.inline)
}
}
}

SwiftUI - Animating a state variable that reloads a view causes it to breifly fade out and back in

I would like to show a bunch of vertical bars, and on the click of a button have the first one swap places with a randomly selected one. I want this to be animated and the gif below shows the closest I've come, but as you can see, the entire set of vertical bars flashes briefly on each button click, which I do not want.
I've tried a few different approaches. The most elegant one I think would be to have the array of values which I iterate through to show the bars be a state variable, and when the array is sorted, the list just reloads and the swapping is animated. However, this didn't result in a swapping effect. It would just shrink and grow the respective bars to match the sizes of the array elements that were swapped :( I still feel like this might be the best approach, so I'm open to completely changing the implementation.
So the closest I've come is what you see in the gif, but it's hacky and I don't like the flashing of the entire view when it reloads. I'm using matchedGeometryEffect (hero animation) and even to get that working, I had to have a state variable that would reload the view. As you will see in the code below, this forces me to have an if/else even if I am just reloading the view under either condition. So I don't truly need the if(animate){} else {}, but using a hero animation forces me to.
Here's my code:
import SwiftUI
class SortElement: Identifiable{
var id: Int
var name: String
var color: Color
var height: CGFloat
init(id: Int, name: String, color: Color, height: CGFloat){
self.id = id
self.name = name
self.color = color
self.height = height
}
}
struct SortArrayAnimationDemo: View {
#Namespace private var animationSwap
#State private var animate: Bool = false
private static var sortableElements: [SortElement] = [
SortElement(id: 6, name:"6", color: Color(UIColor.lightGray), height: 60),
SortElement(id: 2, name:"2", color: Color(UIColor.lightGray), height: 20),
SortElement(id: 5, name:"5", color: Color(UIColor.lightGray), height: 50),
SortElement(id: 1, name:"1", color: Color(UIColor.lightGray), height: 10),
SortElement(id: 3, name:"3", color: Color(UIColor.lightGray), height: 30),
SortElement(id: 9, name:"9", color: Color(UIColor.lightGray), height: 90),
SortElement(id: 4, name:"4", color: Color(UIColor.lightGray), height: 40),
SortElement(id: 8, name:"8", color: Color(UIColor.lightGray), height: 80)
]
var body: some View {
VStack{
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.blue)
.frame(width: 200.0, height: 20.0)
if(animate){
fetchSwappingView()
}else {
fetchSwappingView()
}
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.blue)
.frame(width: 200.0, height: 20.0)
Button(action: { doAnimate() }) { Text("Swap!") }.padding(.top, 30)
}//vstack
}
#ViewBuilder
private func fetchSwappingView() -> some View {
HStack(alignment: .bottom){
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.red)
.frame(width: 30.0, height: 100.0)
ForEach(0..<SortArrayAnimationDemo.sortableElements.count) { i in
let sortableElement = SortArrayAnimationDemo.sortableElements[i]
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.gray)
.frame(width: 20.0, height: sortableElement.height)
.matchedGeometryEffect(id: sortableElement.id,
in: animationSwap,
properties: .position)
}
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.red)
.frame(width: 30.0, height: 100.0)
}//hstack
}
private func doAnimate() -> Void {
let randomIndex = Int.random(in: 1..<8)
let tmpLeftSortableElement: SortElement = SortArrayAnimationDemo.sortableElements[0]
SortArrayAnimationDemo.sortableElements[0] = SortArrayAnimationDemo.sortableElements[randomIndex]
SortArrayAnimationDemo.sortableElements[randomIndex] = tmpLeftSortableElement
withAnimation(.spring(dampingFraction: 0.7).speed(1.5).delay(0.05)){
animate.toggle()
}
}
}
Your code has a couple problems. First, you're working around the immutability of structs with this:
private static var sortableElements: [SortElement] = [
static isn't going to make SwiftUI refresh the view. I think you found this out too, so added another #State:
#State private var animate: Bool = false
...
if (animate) {
fetchSwappingView()
} else {
fetchSwappingView()
}
Well... this is where your flashing is coming from. The default transition applied to an if-else is a simple fade, which is what you're seeing.
But, if you think about it, this if-else doesn't make any sense. There's no need for an intermediary animate state — just let SwiftUI do the work!
You were initially on the right track.
The most elegant one I think would be to have the array of values which I iterate through to show the bars be a state variable, and when the array is sorted, the list just reloads and the swapping is animated. However, this didn't result in a swapping effect. It would just shrink and grow the respective bars to match the sizes of the array elements that were swapped :( I still feel like this might be the best approach, so I'm open to completely changing the implementation.
As you thought, the better way would be to just have a single #State array of SortElements. I'll get to the swapping effect problem in a bit — first, replace private static var with #State private var:
#State private var sortableElements: [SortElement] = [
This makes it possible to directly modify sortableElements. Now, in your doAnimate function, just set sortableElements instead of doing all sorts of weird stuff.
private func doAnimate() -> Void {
let randomIndex = Int.random(in: 1..<8)
let tmpLeftSortableElement: SortElement = sortableElements[0]
withAnimation(.spring(dampingFraction: 0.7).speed(1.5).delay(0.05)){
sortableElements[0] = sortableElements[randomIndex]
sortableElements[randomIndex] = tmpLeftSortableElement
}
}
Don't forget to also replace
if (animate) {
fetchSwappingView()
} else {
fetchSwappingView()
}
with:
fetchSwappingView()
At this point, your result should look like this:
This matches your problem description: the heights change fine, but there's no animation!
this didn't result in a swapping effect. It would just shrink and grow the respective bars to match the sizes of the array elements that were swapped :(
The problem is here:
ForEach(0..<sortableElements.count) { i in
Since you're simply looping over sortableElements.count, SwiftUI has no idea how the order changed. Instead, you should directly loop over sortableElements. The array's elements, SortElement, all conform to Identifiable — so SwiftUI can now determine how the order changed.
ForEach(sortableElements) { element in
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.gray)
.frame(width: 20.0, height: element.height)
.matchedGeometryEffect(
id: element.id,
in: animationSwap,
properties: .position
)
}
Here's the final code:
struct SortArrayAnimationDemo: View {
#Namespace private var animationSwap
#State private var sortableElements: [SortElement] = [
SortElement(id: 6, name:"6", color: Color(UIColor.lightGray), height: 60),
SortElement(id: 2, name:"2", color: Color(UIColor.lightGray), height: 20),
SortElement(id: 5, name:"5", color: Color(UIColor.lightGray), height: 50),
SortElement(id: 1, name:"1", color: Color(UIColor.lightGray), height: 10),
SortElement(id: 3, name:"3", color: Color(UIColor.lightGray), height: 30),
SortElement(id: 9, name:"9", color: Color(UIColor.lightGray), height: 90),
SortElement(id: 4, name:"4", color: Color(UIColor.lightGray), height: 40),
SortElement(id: 8, name:"8", color: Color(UIColor.lightGray), height: 80)
]
var body: some View {
VStack{
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.blue)
.frame(width: 200.0, height: 20.0)
fetchSwappingView() /// NO if else needed!
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.blue)
.frame(width: 200.0, height: 20.0)
Button(action: { doAnimate() }) { Text("Swap!") }.padding(.top, 30)
}//vstack
}
#ViewBuilder
private func fetchSwappingView() -> some View {
HStack(alignment: .bottom){
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.red)
.frame(width: 30.0, height: 100.0)
/// directly loop over `sortableElements` instead of its count
ForEach(sortableElements) { element in
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.gray)
.frame(width: 20.0, height: element.height)
.matchedGeometryEffect(
id: element.id,
in: animationSwap,
properties: .position
)
}
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.red)
.frame(width: 30.0, height: 100.0)
}//hstack
}
private func doAnimate() -> Void {
let randomIndex = Int.random(in: 1..<8)
let tmpLeftSortableElement: SortElement = sortableElements[0]
/// directly set `sortableElements`
withAnimation(.spring(dampingFraction: 0.7).speed(1.5).delay(0.05)){
sortableElements[0] = sortableElements[randomIndex]
sortableElements[randomIndex] = tmpLeftSortableElement
}
}
}
Result:

SwiftUI: Shadow on view in VStack?

I have the following code:
struct ViewA: View {
var body: some View {
Rectangle()
.fill(Color(.yellow))
}
}
struct ViewB: View {
var body: some View {
Rectangle()
.fill(Color(.white))
}
}
struct ViewC: View {
var body: some View {
Rectangle()
.fill(Color(.blue))
}
}
struct TestView: View {
var body: some View {
GeometryReader { geo in
VStack(spacing: 0) {
ViewA()
.frame(width: geo.size.width, height: geo.size.width/4, alignment: .center)
.shadow(color: .black, radius: 10, x: 0, y: 10)
ViewB()
ViewC()
.frame(width: geo.size.width, height: 100, alignment: .center)
.shadow(color: .black, radius: 10, x: 0, y: 0)
.opacity(0.8)
}
}
}
}
It draws:
The shadow at the bottom Blue over White view (ViewC over ViewB) shows up.
I want the yellow view (ViewA) to drop a shadow on top of the white view.
I want the white view to appear as if it were under both the top view (yellow) and the bottom view (blue).
I am not sure how to organize the views so that the top view also drops shadow on the middle view.
How would I accomplish this?
You could apply zindex modifier to ViewA. For example .zIndex(.infinity). It will put ViewA on top of everything.
https://developer.apple.com/documentation/swiftui/view/zindex(_:)
If you place the views in a ZStack with ViewB behind ViewA and ViewC you will see the shadow:
GeometryReader { geo in
ZStack {
ViewB()
VStack(spacing: 0) {
ViewA()
.frame(
width: geo.size.width,
height: geo.size.width/4,
alignment: .center)
.shadow(
color: .black,
radius: 10,
x: 0, y: 0)
Spacer()
ViewC()
.frame(
width: geo.size.width,
height: 100,
alignment: .center)
.shadow(
color: .black,
radius: 10,
x: 0, y: 0)
.opacity(0.8)
}
}
}