Binding in SwiftUI fails to work inside of a loop - xcode

For my understanding, I've written the following code which expands / collapses a section inside of a list.
struct WORKING_CollapsableListView: View {
#State var sectionExpansionStates = [true, true, true]
var body: some View {
VStack {
List {
Section(header: CollapsableSectionHeader(expansionState: self.$sectionExpansionStates[0])) {
if self.sectionExpansionStates[0] {
ForEach(0..<10) { item in
Text("\(item) is \(self.sectionExpansionStates[0] ? "Expanded" : "Collapsed")")
.frame(height: self.sectionExpansionStates[0] ? 10 : 10)
}
}
}
Section(header: CollapsableSectionHeader(expansionState: self.$sectionExpansionStates[1])) {
if self.sectionExpansionStates[1] {
ForEach(0..<10) { item in
Text("\(item) is \(self.sectionExpansionStates[1] ? "Expanded" : "Collapsed")")
.frame(height: self.sectionExpansionStates[1] ? 10 : 10)
}
}
}
Section(header: CollapsableSectionHeader(expansionState: self.$sectionExpansionStates[2])) {
if self.sectionExpansionStates[2] {
ForEach(0..<10) { item in
Text("\(item) is \(self.sectionExpansionStates[2] ? "Expanded" : "Collapsed")")
.frame(height: self.sectionExpansionStates[2] ? 10 : 10)
}
}
}
}
}
}
}
struct CollapsableSectionHeader: View {
#Binding var expansionState: Bool
var body: some View {
Button(action: {
self.expansionState.toggle()
}) {
Text("HEADER: \(expansionState ? "Expanded" : "Collapsed")")
.bold()
}
}
}
This works as expected. However the following code does NOT work. All I've done is replaced the multiple sections with a ForEach. This code should be identical in its behavior, but nothing happens when I tap on the section headers. What am I missing? It's as though the binding isn't working.
struct NOT_WORKING_CollapsableListView: View {
#State var sectionExpansionStates = [true, true, true]
var body: some View {
VStack {
List {
ForEach(0 ..< 3) { section in
Section(header: CollapsableSectionHeader(expansionState: self.$sectionExpansionStates[section])) {
if self.sectionExpansionStates[section] {
ForEach(0..<10) { item in
Text("\(item) is \(self.sectionExpansionStates[section] ? "Expanded" : "Collapsed")")
.frame(height: self.sectionExpansionStates[section] ? 10 : 10)
}
}
}
}
}
}
}
}

It is due to statically_ranged_ForEach... as I experienced here on SO it is most confused concept in SwiftUI.. anyway - the solution is to use dynamic container of explicit models for sections.
Here is simplified working demo of your code (but the idea should be easily adoptable to your not provided components).
Tested with Xcode 11.4 / iOS 13.4
// simple demo model for sections
struct SectionModel: Identifiable {
let id: Int
var expanded = true
}
struct TestCollapsableListView: View {
// dynamic container with model, state is triggered
#State var sections = [SectionModel(id: 0), SectionModel(id: 1), SectionModel(id: 2)]
var body: some View {
VStack {
List {
ForEach(sections) { section in
Section(header: Button("Section \(section.id)") { self.sections[section.id].expanded.toggle() }) {
if section.expanded {
ForEach(0..<10) { item in
Text("\(item) is \(section.expanded ? "Expanded" : "Collapsed")")
.frame(height: section.expanded ? 10 : 10)
}
}
}
}
}
}
}
}

Related

SwiftUI - Picker .onChange and didSet

I'm trying to achieve the behavior in the attached GIF:
Sorry for the High Speed, I had to compress it dramatically to be able to upload it here. The App is "Documents" from Readdle if you want to have a look on your own.
Anyways: I'm exactly trying to achieve this behavior (sorting and filtering, including the dynamic arrow up down icon).
I tried the following approach, however I'm not able to achieve this "ontap" expierience. On Change only triggers when I change the value but when I want to sort an existing value ascending and descending it's not working (which is obvious because it's not changing). I already played around with "didSet" but this also did not work.
Do you have an idea how this can be accomplished?
Below is my code:
import SwiftUI
struct ContentView: View {
#State var selection = 0
#State var sortByAsc = true
#State var filterColumn = "A"
//Test to set case via picker but picter doesnt execute didSet
#State var myFilterTest: MyFilters = .alphabetical {
didSet {
switch myFilterTest {
case .creationDate:
sortByAsc.toggle()
print("c")
case .rating:
sortByAsc.toggle()
print("b")
case .alphabetical:
sortByAsc.toggle()
print("a")
}
}
}
var body: some View {
NavigationView {
Text("Hello, World!")
.padding()
.navigationTitle("SwiftUI")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Menu(content: {
Picker("My Picker", selection: $selection) {
Label("Title", systemImage: sortByAsc ? "arrow.down" : "arrow.up")
.tag(0)
Label("Rating", systemImage: sortByAsc ? "arrow.down" : "arrow.up")
.tag(1)
.onTapGesture {
print("tap")
}
}
.onChange(of: selection) { tag in
print("Selected Tag: \(tag)")
sortByAsc.toggle()
if(tag == 0) {
filterColumn = "Title"
}
if(tag == 1) {
filterColumn = "Rating"
}
}
}, label: {
Image(systemName: "ellipsis.circle")
})
}
}
}
}
}
enum MyFilters: CaseIterable {
case alphabetical
case rating
case creationDate
}
Solved It. Here's the Code:
struct PickerView: View {
#State private var pickerIndex = 0
#State private var previousPickerIndex = 0
#State var sortByAsc = true
var body: some View {
let pickerSelection = Binding<Int>(get: {
return self.pickerIndex
}, set: {
self.pickerIndex = $0
if(pickerIndex == previousPickerIndex) {
sortByAsc.toggle()
}
previousPickerIndex = pickerIndex
})
NavigationView {
Text("Hello, World!")
.padding()
.navigationTitle("SwiftUI")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Menu(content: {
Picker("My Picker", selection: pickerSelection) {
ForEach(0..<4, id: \.self) { index in
Label("Title \(index)", systemImage: getSortingImage(menuItem: index))
.tag(index)
}
}
}, label: {
Image(systemName: "ellipsis.circle")
})
}
}
}
}
func getSortingImage(menuItem: Int) -> String {
if(menuItem == pickerIndex) {
if(sortByAsc) {
return "arrow.down"}
else {
return "arrow.up"
}
}
else {
return ""
}
}
}

SwiftUI for macOS - trigger sheet .onDismiss problem

In a multiplatform app I'm showing a sheet to collect a small amount of user input. On iOS, when the sheet is dismissed, the relevant .onDismiss method is called but not on macOS.
I've read that having the .onDismiss in the List can cause problems so I've attached it to the button itself with no improvement. I've also tried passing the isPresented binding through and toggling that within the sheet itself to dismiss, but again with no success.
I am employing a NavigationView but removing that makes no difference. The following simplified example demonstrates my problem. Any ideas? Should I even be using a sheet for this purpose on macOS?
I just want to make clear that I have no problem closing the sheet. The other questions I found were regarding problems closing the sheet - I can do that fine.
import SwiftUI
#main
struct SheetTestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
ListView()
}
}
}
The List view.
struct ListView: View {
#State private var isPresented: Bool = false
var body: some View {
VStack {
Text("Patterns").font(.title)
Button(action: {
isPresented = true
}, label: {
Text("Add")
})
.sheet(isPresented: $isPresented, onDismiss: {
doSomethingAfter()
}) {
TestSheetView()
}
List {
Text("Bingo")
Text("Bongo")
Text("Banjo")
}
.onAppear(perform: {
doSomethingBefore()
})
}
}
func doSomethingBefore() {
print("Johnny")
}
func doSomethingAfter() {
print("Cash")
}
}
This is the sheet view.
struct TestSheetView: View {
#Environment(\.presentationMode) var presentationMode
#State private var name = ""
var body: some View {
Form {
TextField("Enter name", text: $name)
.padding()
HStack {
Spacer()
Button("Save") {
presentationMode.wrappedValue.dismiss()
}
Spacer()
}
}
.frame(minWidth: 300, minHeight: 300)
.navigationTitle("Jedward")
}
}
Bad issue.. you are right. OnDismiss is not called. Here is a workaround with Proxybinding
var body: some View {
VStack {
Text("Patterns").font(.title)
Button(action: {
isPresented = true
}, label: {
Text("Add")
})
List {
Text("Bingo")
Text("Bongo")
Text("Banjo")
}
.onAppear(perform: {
doSomethingBefore()
})
}
.sheet(isPresented: Binding<Bool>(
get: {
isPresented
}, set: {
isPresented = $0
if !$0 {
doSomethingAfter()
}
})) {
TestSheetView()
}
}

#State var doesn't update when changing the value outside the view

I need to declare the checkBox array using "#State" if I want to use it inside the view using $checkBox and it works fine but when I want to update the toggles (1 or more elements of the array) in a function outside the view, the array is not updated. I tried to declare it using #Binding and #Published but without success. I saw many similar Q&A but I didn't find a solution for my case. This is my code:
struct CheckboxStyle: ToggleStyle {
func makeBody(configuration: Self.Configuration) -> some View {
return HStack {
Image(systemName: configuration.isOn ? "checkmark.circle.fill" : "circle")
.resizable()
.frame(width: 24, height: 24)
.foregroundColor(configuration.isOn ? .green : .gray)
.onTapGesture { configuration.isOn.toggle() }
configuration.label
}
}
}
struct ContentView: View {
#State var checkBox = Array(repeating: false, count: 14)
let checkBoxName: [LocalizedStringKey] = ["checkPressure", "checkVisibility", "checkCloudCover", "checkAirTemp", "checkWaterTemp", "checkWindDir", "checkWindSpeed", "checkWindGust", "checkCurrentDir", "checkCurrentSpeed", "checkSwellDir", "checkWaveHeight", "checkWavePeriod", "checkTideHeight"]
var body: some View {
ScrollView {
VStack(alignment: .leading) {
Group {
ForEach(0..<7) { t in
Toggle(isOn: $checkBox[t], label: {
Text(checkBoxName[t]).font(.footnote).fontWeight(.light)
}).toggleStyle(CheckboxStyle()).padding(5)
}
}
Group {
ForEach(7..<14) { t in
Toggle(isOn: $checkBox[t], label: {
Text(checkBoxName[t]).font(.footnote).fontWeight(.light)
}).toggleStyle(CheckboxStyle()).padding(5)
}
}
}
}
}
}
Thx for help

How to toggle the visibility of the third pane of NavigationView?

Assuming the following NavigationView:
Struct ContentView: View {
#State var showRigthPane: Bool = true
var body: some View {
NavigationView {
Sidebar()
MiddlePane()
RightPane()
}.toolbar {
ToolbarItem(placement: .navigation) {
Button(action: toggleSidebar, label: {Image(systemName: "sidebar.left")})
}
ToolbarItem(placement: .primaryAction) {
Button(action: self.toggleRightPane, label: { Image() })
}
}
}
private func toggleRightPane() {
// ?
}
// collapsing sidebar - this works
private func toggleSidebar() {
NSApp.keyWindow?.initialFirstResponder?.tryToPerform(
#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
}
}
How can I implement the toggleRightPane() function to toggle the visibility of the right pane?
Updated to use a calculated property returning two different navigation views. Still odd behavior with sidebar, but with a work-around it is functional. Hopefully someone can figure out the sidebar behavior.
struct ToggleThirdPaneView: View {
#State var showRigthPane: Bool = true
var body: some View {
VStack {
navigationView
}
.navigationTitle("Show and Hide")
}
var navigationView : some View {
if showRigthPane {
return AnyView(NavigationView {
VStack {
Text("left")
}
.toolbar {
Button(action: { showRigthPane.toggle() }) {
Label("Add Item", systemImage: showRigthPane ? "rectangle.split.3x1" : "rectangle.split.2x1")
}
}
Text("middle")
}
)
} else {
return AnyView(NavigationView {
VStack {
Text("left")
}
.toolbar {
Button(action: { showRigthPane.toggle() }) {
Label("Add Item", systemImage: showRigthPane ? "rectangle.split.3x1" : "rectangle.split.2x1")
}
}
Text("middle")
Text("right")
})
}
}
}
Try the following (cannot test)
struct ContentView: View {
#State private var showRigthPane = true
var body: some View {
NavigationView {
Sidebar()
MiddlePane()
if showRigthPane { // << here !!
RightPane()
}
}.toolbar {
ToolbarItem(placement: .primaryAction) {
Button(action: self.toggleRightPane, label: { Image() })
}
}
}
private func toggleRightPane() {
withAnimation {
self.showRigthPane.toggle() // << here !!
}
}
}

Transition from one view to another SwiftUI

How can I transition from one View to another? Is there push / pop like in UIKit? Do I have to use a NavigationView and if so how?
Using a NavigationView
NavigationViews are tied to NavigationButton (AFAIK that is the only way to trigger a segue). Here is a simple example where the main view can transition to a detail view.
struct DetailView : View {
let value: String
var body : some View {
Text("Full View: \(value)")
}
}
struct MainView : View {
var body : some View {
NavigationView {
NavigationButton(destination: DetailView(value: "Hello World"),
label: { Text("Click Me") })
}
}
}
This will automatically handle transitions and add a back button.
Using State
Another approach is to use a stateful variable to determine if the child view is displayed. Here is another simple example:
struct DetailView : View {
let value: String
let onDone: () -> Void
var body : some View {
VStack {
Text("Full View: \(value)")
Button(action: onDone, label: { Text("Back") })
}
}
}
struct MainView : View {
#State var displaySubview = false
var body : some View {
VStack {
if displaySubview {
DetailView(value: "Hello World") {
self.displaySubview = false
}
} else {
Button(action: {
self.displaySubview = true
}, label: { Text("Click Me") })
}
}
}
}
This approach requires you to implement more of the UI elements, but it also allows for more control over views.
It works for me
struct ContentView : View {
var body : some View {
NavigationView {
NavigationLink(destination: DetailView(), label: { Text("To Detail")})
}
}}

Resources