SwiftUI Expand Lists One-At-A-Time, Auto Collapse - ios

I'm trying to build a view with several collapsed lists, only the headers showing at first. When you tap on a header, its list should expand. Then, with the first list is expanded, if you tap on the header of another list, the first list should automatically collapse while the second list expands. So on and so forth, so only one list is visible at a time.
The code below works great to show multiple lists at the same time and they all expand and collapse with a tap, but I can't figure out what to do to make the already open lists collapse when I tap to expand a collapsed list.
Here's the code (sorry, kind of long):
import SwiftUI
struct Task: Identifiable {
let id: String = UUID().uuidString
let title: String
let subtask: [Subtask]
}
struct Subtask: Identifiable {
let id: String = UUID().uuidString
let title: String
}
struct SubtaskCell: View {
let task: Subtask
var body: some View {
HStack {
Image(systemName: "circle")
.foregroundColor(Color.primary.opacity(0.2))
Text(task.title)
}
}
}
struct TaskCell: View {
var task: Task
#State private var isExpanded = false
var body: some View {
content
.padding(.leading)
.frame(maxWidth: .infinity)
}
private var content: some View {
VStack(alignment: .leading, spacing: 8) {
header
if isExpanded {
Group {
List(task.subtask) { subtask in
SubtaskCell(task: subtask)
}
}
.padding(.leading)
}
Divider()
}
}
private var header: some View {
HStack {
Image(systemName: "square")
.foregroundColor(Color.primary.opacity(0.2))
Text(task.title)
}
.padding(.vertical, 4)
.onTapGesture {
withAnimation {
isExpanded.toggle()
}
}
}
}
struct ContentView: View {
//sample data
private let tasks: [Task] = [
Task(
title: "Create playground",
subtask: [
Subtask(title: "Cover image"),
Subtask(title: "Screenshots"),
]
),
Task(
title: "Write article",
subtask: [
Subtask(title: "Cover image"),
Subtask(title: "Screenshots"),
]
),
Task(
title: "Prepare assets",
subtask: [
Subtask(title: "Cover image"),
Subtask(title: "Screenshots"),
]
),
Task(
title: "Publish article",
subtask: [
Subtask(title: "Cover image"),
Subtask(title: "Screenshots"),
]
),
]
var body: some View {
NavigationView {
VStack(alignment: .leading) {
ForEach(tasks) { task in
TaskCell(task: task)
.animation(.default)
}
Spacer()
}
}
}
}
Thanks ahead for any help!
EDIT: Here's the collapse functionality to go with the accepted solution below:
Update the onTapGesture in private var header: some View to look like this:
.onTapGesture {
withAnimation {
if task.isExpanded {
viewmodel.collapse(task)
} else {
viewmodel.expand(task)
}
}
}
Then add the collapse function to class Viewmodel
func collapse(_ taks: TaskModel) {
var tasks = self.tasks
tasks = tasks.map {
var tempVar = $0
tempVar.isExpanded = false
return tempVar
}
self.tasks = tasks
}
That's it! Fully working as requested!

I think the best way to achieve this is to move the logic to a viewmodel.
struct TaskModel: Identifiable {
let id: String = UUID().uuidString
let title: String
let subtask: [Subtask]
var isExpanded: Bool = false // moved state variable to the model
}
struct Subtask: Identifiable {
let id: String = UUID().uuidString
let title: String
}
struct SubtaskCell: View {
let task: Subtask
var body: some View {
HStack {
Image(systemName: "circle")
.foregroundColor(Color.primary.opacity(0.2))
Text(task.title)
}
}
}
struct TaskCell: View {
var task: TaskModel
#EnvironmentObject private var viewmodel: Viewmodel //removed state here and added viewmodel from environment
var body: some View {
content
.padding(.leading)
.frame(maxWidth: .infinity)
}
private var content: some View {
VStack(alignment: .leading, spacing: 8) {
header
if task.isExpanded {
Group {
List(task.subtask) { subtask in
SubtaskCell(task: subtask)
}
}
.padding(.leading)
}
Divider()
}
}
private var header: some View {
HStack {
Image(systemName: "square")
.foregroundColor(Color.primary.opacity(0.2))
Text(task.title)
}
.padding(.vertical, 4)
.onTapGesture {
withAnimation {
viewmodel.expand(task) //handle expand / collapse here
}
}
}
}
struct ContentView: View {
#StateObject private var viewmodel: Viewmodel = Viewmodel() //Create viewmodel here
var body: some View {
NavigationView {
VStack(alignment: .leading) {
ForEach(viewmodel.tasks) { task in //use viewmodel tasks here
TaskCell(task: task)
.animation(.default)
.environmentObject(viewmodel)
}
Spacer()
}
}
}
}
class Viewmodel: ObservableObject{
#Published var tasks: [TaskModel] = [
TaskModel(
title: "Create playground",
subtask: [
Subtask(title: "Cover image"),
Subtask(title: "Screenshots"),
]
),
TaskModel(
title: "Write article",
subtask: [
Subtask(title: "Cover image"),
Subtask(title: "Screenshots"),
]
),
TaskModel(
title: "Prepare assets",
subtask: [
Subtask(title: "Cover image"),
Subtask(title: "Screenshots"),
]
),
TaskModel(
title: "Publish article",
subtask: [
Subtask(title: "Cover image"),
Subtask(title: "Screenshots"),
]
),
]
func expand(_ task: TaskModel){
//copy tasks to local variable to avoid refreshing multiple times
var tasks = self.tasks
//create new task array with isExpanded set
tasks = tasks.map{
var tempVar = $0
tempVar.isExpanded = $0.id == task.id
return tempVar
}
// assign array to update view
self.tasks = tasks
}
}
Notes:
Renamed your task model as it is a very bad idea to name somthing with a name that is allready used by the language
This only handles expanding. But implementing collapsing shouldn´t be to hard :)
Edit:
if you dont want a viewmodel you can use a binding as alternative:
Add to your containerview:
#State private var selectedId: String?
change body to:
NavigationView {
VStack(alignment: .leading) {
ForEach(tasks) { task in
TaskCell(task: task, selectedId: $selectedId)
.animation(.default)
}
Spacer()
}
}
and change your TaskCell to:
struct TaskCell: View {
var task: TaskModel
#Binding var selectedId: String?
var body: some View {
content
.padding(.leading)
.frame(maxWidth: .infinity)
}
private var content: some View {
VStack(alignment: .leading, spacing: 8) {
header
if selectedId == task.id {
Group {
List(task.subtask) { subtask in
SubtaskCell(task: subtask)
}
}
.padding(.leading)
}
Divider()
}
}
private var header: some View {
HStack {
Image(systemName: "square")
.foregroundColor(Color.primary.opacity(0.2))
Text(task.title)
}
.padding(.vertical, 4)
.onTapGesture {
withAnimation {
selectedId = selectedId == task.id ? nil : task.id
}
}
}
}

Related

Swiftui items get duplicated in all views when added to a single custom view

I'm struggling with the following issue: I'm trying to build a very simple app that lets you add items in a dedicated view that can be collapsed. I managed to write a simple function that lets me add multiple of these custom collapsable views. It's my first app so I wanted to follow the MVVM protocol. I think I got confused along the way because now every item I add gets automatically added to all the custom collapsable views I made. Is there any way to fix this? I thought using the UUID would solve this issue.. I'm guessing that I have to customise the "saveButtonPressed" function, but I don't know how to tell it to only add the item to the view where I pressed the "plus" button..
Here are the Models for the individual items and the collapsable view:
struct ItemModel: Identifiable, Equatable {
let id: String
let title: String
init(id: String = UUID().uuidString, title: String) {
self.id = id
self.title = title
}
func updateCompletion() -> ItemModel {
return ItemModel(id: id, title: title)
}
}
--
import Foundation
struct CollapsableItem: Equatable, Identifiable, Hashable {
let id: String
var title: String
init(id: String = UUID().uuidString, title: String) {
self.id = id
self.title = title
}
func updateCompletion() -> CollapsableItem {
return CollapsableItem(id: id, title: title)
}
}
These are my two ViewModels:
class ListViewModel: ObservableObject {
#Published var items: [ItemModel] = []
init() {
getItems()
}
func getItems() {
let newItems = [
ItemModel(title: "List Item1"),
ItemModel(title: "List Item2"),
ItemModel(title: "List Item3"),
]
items.append(contentsOf: newItems)
}
func addItem(title: String) {
let newItem = ItemModel(title: title)
items.append(newItem)
}
func updateItem(item: ItemModel) {
if let index = items.firstIndex(where: { $0.id == item.id}) {
items[index] = item.updateCompletion()
}
}
}
--
class CollapsedViewModel: ObservableObject {
#Published var collapsableItems: [CollapsableItem] = []
#Published var id = UUID().uuidString
init() {
getCollapsableItems()
}
func getCollapsableItems() {
let newCollapsableItems = [
CollapsableItem(title: "Wake up")
]
collapsableItems.append(contentsOf: newCollapsableItems)
}
func addCollapsableItem(title: String) {
let newCollapsableItem = CollapsableItem(title: title)
collapsableItems.append(newCollapsableItem)
}
func updateCollapsableItem(collapsableItem: CollapsableItem) {
if let index = collapsableItems.firstIndex(where: { $0.id ==
collapsableItem.id}) {
collapsableItems[index] =
collapsableItem.updateCompletion()
}
}
}
The item view:
struct ListRowView: View {
#EnvironmentObject var listViewModel: ListViewModel
let item: ItemModel
var body: some View {
HStack() {
Text(item.title)
.font(.body)
.fontWeight(.bold)
.foregroundColor(.white)
.multilineTextAlignment(.center)
.lineLimit(1)
.frame(width: 232, height: 16)
}
.padding( )
.frame(width: 396, height: 56)
.background(.gray)
.cornerRadius(12.0)
}
}
The collapsable view:
struct CollapsedView2<Content: View>: View {
#State var collapsableItem: CollapsableItem
#EnvironmentObject var collapsedViewModel: CollapsedViewModel
#State private var collapsed: Bool = true
#EnvironmentObject var listViewModel: ListViewModel
#State var label: () -> Text
#State var content: () -> Content
#State private var show = true
var body: some View {
ZStack{
VStack {
HStack{
Button(
action: { self.collapsed.toggle() },
label: {
HStack() {
Text("Hello")
.font(.title2.bold())
Spacer()
Image(systemName: self.collapsed ? "chevron.down" :
"chevron.up")
}
.padding(.bottom, 1)
.background(Color.white.opacity(0.01))
}
)
.buttonStyle(PlainButtonStyle())
Button(action: saveButtonPressed, label: {
Image(systemName: "plus")
.font(.title2)
.foregroundColor(.white)
})
}
VStack {
self.content()
}
ForEach(listViewModel.items) { item in ListRowView (item: item)
}
.lineLimit(1)
.fixedSize(horizontal: true, vertical: true)
.frame(minWidth: 396, maxWidth: 396, minHeight: 0, maxHeight: collapsed ?
0 : .none)
.animation(.easeInOut(duration: 1.0), value: show)
.clipped()
.transition(.slide)
}
}
}
func saveButtonPressed() {
listViewModel.addItem(title: "Hello")
}
}
and finally the main view:
struct ListView: View {
#EnvironmentObject var listViewModel: ListViewModel
#EnvironmentObject var collapsedViewModel: CollapsedViewModel
var body: some View {
ZStack{
ScrollView{
VStack{
HStack{
Text("MyFirstApp")
.font(.largeTitle.bold())
Button(action: newCollapsablePressed, label: {
Image(systemName: "plus")
.font(.title2)
.foregroundColor(.white)
})
}
.padding()
.padding(.leading)
ForEach(collapsedViewModel.collapsableItems) { collapsableItem in
CollapsedView2 (collapsableItem: collapsableItem,
label: { Text("") .font(.title2.bold()) },
content: {
HStack {
Text("")
Spacer() }
.frame(maxWidth: .infinity)
})
}
.padding()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.statusBar(hidden: false)
.navigationBarHidden(true)
}
}
func newCollapsablePressed() {
collapsedViewModel.addCollapsableItem(title: "hello2")
}
}
Would love to understand how I could fix this!
There is the anwser for your comment about add item in each CollapsedView2.
Because ListViewModel is not ObservableObject (ListViewModel is difference from each CollapsableItem). You should use "#State var items: [ItemModel]".
struct CollapsedView2<Content: View>: View {
#State var collapsableItem: CollapsableItem
// #State var listViewModel = ListViewModel()
#State var collapsed: Bool = true
#State var label: () -> Text
#State var content: () -> Content
#State private var show = true
#State var items: [ItemModel] = []
#State var count = 1
var body: some View {
VStack {
HStack{
Text("Hello")
.font(.title2.bold())
Spacer()
Button( action: { self.collapsed.toggle() },
label: {
Image(systemName: self.collapsed ? "chevron.down" : "chevron.up")
}
)
.buttonStyle(PlainButtonStyle())
Button(action: saveButtonPressed, label: {
Image(systemName: "plus")
.font(.title2)
// .foregroundColor(.white)
})
}
VStack {
self.content()
}
ForEach(items) { item in
ListRowView (item: item)
}
.lineLimit(1)
.fixedSize(horizontal: true, vertical: true)
.frame(minHeight: 0, maxHeight: collapsed ? 0 : .none)
.animation(.easeInOut(duration: 1.0), value: show)
.clipped()
.transition(.slide)
}
}
func saveButtonPressed() {
addItem(title: "Hello \(count)")
count += 1
}
func addItem(title: String) {
let newItem = ItemModel(title: title)
items.append(newItem)
}
func updateItem(item: ItemModel) {
if let index = items.firstIndex(where: { $0.id == item.id}) {
items[index] = item.updateCompletion()
}
}
}
There is the anwser. Ask me if you have some questions
struct ListView: View {
#StateObject var collapsedViewModel = CollapsedViewModel()
var body: some View {
ScrollView{
VStack{
HStack{
Text("MyFirstApp")
.font(.largeTitle.bold())
Button(action: newCollapsablePressed, label: {
Image(systemName: "plus")
.font(.title2)
// .foregroundColor(.white)
})
}
ForEach(collapsedViewModel.collapsableItems) { collapsableItem in
CollapsedView2 (collapsableItem: collapsableItem,
label: { Text("") .font(.title2.bold()) },
content: {
HStack {
Text("")
Spacer()
}
})
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.statusBar(hidden: false)
.navigationBarHidden(true)
}
func newCollapsablePressed() {
collapsedViewModel.addCollapsableItem(title: "hello2")
}
}
struct CollapsedView2<Content: View>: View {
#State var collapsableItem: CollapsableItem
#State var listViewModel = ListViewModel()
#State var collapsed: Bool = true
#State var label: () -> Text
#State var content: () -> Content
#State private var show = true
var body: some View {
VStack {
HStack{
Button( action: { self.collapsed.toggle() },
label: {
HStack() {
Text("Hello")
.font(.title2.bold())
Spacer()
Image(systemName: self.collapsed ? "chevron.down" : "chevron.up")
}
.padding(.bottom, 1)
.background(Color.white.opacity(0.01))
}
)
.buttonStyle(PlainButtonStyle())
Button(action: saveButtonPressed, label: {
Image(systemName: "plus")
.font(.title2)
.foregroundColor(.white)
})
}
VStack {
self.content()
}
ForEach(listViewModel.items) { item in
ListRowView (item: item)
}
.lineLimit(1)
.fixedSize(horizontal: true, vertical: true)
.frame(minHeight: 0, maxHeight: collapsed ? 0 : .none)
.animation(.easeInOut(duration: 1.0), value: show)
.clipped()
.transition(.slide)
}
}
func saveButtonPressed() {
listViewModel.addItem(title: "Hello")
}
}
struct ListRowView: View {
let item: ItemModel
var body: some View {
HStack() {
Text(item.title)
.font(.body)
.fontWeight(.bold)
.foregroundColor(.white)
.multilineTextAlignment(.center)
.lineLimit(1)
.frame(width: 232, height: 16)
}
.padding( )
.frame(width: 396, height: 56)
.background(.gray)
.cornerRadius(12.0)
}
}
class ListViewModel {
var items: [ItemModel] = []
init() {
getItems()
}
func getItems() {
let newItems = [
ItemModel(title: "List Item1"),
ItemModel(title: "List Item2"),
ItemModel(title: "List Item3"),
]
items.append(contentsOf: newItems)
}
func addItem(title: String) {
let newItem = ItemModel(title: title)
items.append(newItem)
}
func updateItem(item: ItemModel) {
if let index = items.firstIndex(where: { $0.id == item.id}) {
items[index] = item.updateCompletion()
}
}
}
class CollapsedViewModel: ObservableObject {
#Published var collapsableItems: [CollapsableItem] = []
#Published var id = UUID().uuidString
init() {
getCollapsableItems()
}
func getCollapsableItems() {
let newCollapsableItems = [
CollapsableItem(title: "Wake up")
]
collapsableItems.append(contentsOf: newCollapsableItems)
}
func addCollapsableItem(title: String) {
let newCollapsableItem = CollapsableItem(title: title)
collapsableItems.append(newCollapsableItem)
}
func updateCollapsableItem(collapsableItem: CollapsableItem) {
if let index = collapsableItems.firstIndex(where: { $0.id ==
collapsableItem.id}) {
collapsableItems[index] =
collapsableItem.updateCompletion()
}
}
}
struct CollapsableItem: Equatable, Identifiable, Hashable {
let id: String
var title: String
init(id: String = UUID().uuidString, title: String) {
self.id = id
self.title = title
}
func updateCompletion() -> CollapsableItem {
return CollapsableItem(id: id, title: title)
}
}
struct ItemModel: Identifiable, Equatable {
let id: String
let title: String
init(id: String = UUID().uuidString, title: String) {
self.id = id
self.title = title
}
func updateCompletion() -> ItemModel {
return ItemModel(id: id, title: title)
}
}

using SwiftUI, when scrolling, VStack inside Section shrinks and expands

I'm trying to make simple testing app with Buttons and Options for Button action.
target is iOS 13.0 for backward compatibility.
expected smooth scroll just like other iOS app does, but it stutters.
some VStack is continuously shrink and expand, keep changing scrolls height so it stutters I think.
here's video: https://imgur.com/a/QguC4g0
if I stop just right at stutter-bottom point, there's shrunken VStack.
you can see that shrunken VStack at end of video.
here's the code of main View.
(shrunken Section is SectionH.)
import SwiftUI
struct ContentView: View {
#Environment(\.verticalSizeClass) var verticalSizeClass: UserInterfaceSizeClass?
#Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
var body: some View {
if(verticalSizeClass == .regular && horizontalSizeClass == .compact) {
VStack {
List {
SectionA()
SectionB()
SectionC()
SectionD()
SectionE()
SectionF()
SectionG()
SectionH()
}
OtherView()
}
} else {
HStack {
List {
SectionA()
SectionB()
SectionC()
SectionD()
SectionE()
SectionF()
SectionG()
SectionH()
}
OtherView()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
and heres simple examples of other Sections(A to G are similar.)
import SwiftUI
struct SectionF: View {
#State var bool1 : Bool = true;
#State var text1: String = "text"
#State var text2: String = "text"
#State var text3: String = "text"
#State var text4: String = "text"
var body: some View {
Section(header: Text("Section F")) {
Button{
} label: {
Text("button")
}
VStack(alignment: .leading) {
Button{
} label: {
Text("button: \(bool1 ? "true" : "false")")
}
Toggle("bool", isOn: $bool1)
}
VStack(alignment: .leading) {
Button{
} label: {
Text("button")
}
HStack {
Text("text: ")
TextField("text", text: $text1)
}
HStack {
Text("text: ")
TextField("text", text: $text2)
}
HStack {
Text("text: ")
TextField("text", text: $text3)
}
HStack {
Text("text: ")
TextField("text", text: $text4)
}
}
VStack(alignment: .leading) {
Button{
} label: {
Text("button")
}
HStack {
Text("text: ")
TextField("text", text: $text1)
}
}
}
}
}
struct SectionF_Previews: PreviewProvider {
static var previews: some View {
Form {
SectionF()
}
}
}
and here's dreaded Section H.
import SwiftUI
struct SectionH: View {
#State var text1: String = "text"
#State var text2: String = "text"
#State var picker1: String = "1"
var picker1s = ["1", "2"]
#State var text3: String = "text"
#State var text4: String = "text"
#State var bool1 : Bool = true;
#State var text5: String = "text"
#State var bool2 : Bool = true;
#State var bool3 : Bool = true;
#State var number1: String = "0"
var body: some View {
Section(header: Text("Section H")) {
VStack(alignment: .leading) {
Button{
} label: {
Text("button")
}
HStack {
Text("text: ")
TextField("text", text: $text1)
}
HStack {
Text("text: ")
TextField("text", text: $text2)
}
VStack(alignment: .leading) {
Text("picker: \(picker1)")
Picker("picker", selection: $picker1) {
ForEach(picker1s, id: \.self) {
Text($0)
}
}.pickerStyle(.segmented)
}
HStack {
Text("text: ")
TextField("text", text: $text3)
}
HStack {
Text("text: ")
TextField("text", text: $text4)
}
}
Button {
} label: {
Text("Button")
}
VStack(alignment: .leading) {
Button {
} label: {
Text("Button")
}
VStack {
HStack {
Text("text: ")
TextField("text", text: $text1)
}
HStack {
Text("text: ")
TextField("text", text: $text2)
}
VStack(alignment: .leading) {
Text("picker: \(picker1)")
Picker("picker", selection: $picker1) {
ForEach(picker1s, id: \.self) {
Text($0)
}
}.pickerStyle(.segmented)
}
}
//**this is shrinking VStack!**
VStack {
Toggle("bool", isOn: $bool1)
HStack {
Text("text: ")
TextField("text", text: $text3)
}
HStack {
Text("text: ")
TextField("text", text: $text5)
}
Toggle("bool", isOn: $bool2)
Toggle("bool", isOn: $bool3)
HStack {
Text("number: ")
TextField("number", text: $number1)
}
}
}
}
}
}
struct SectionH_Previews: PreviewProvider {
static var previews: some View {
Form {
SectionH()
}
}
}
here's what I tried:
changing List to Form
changing Sections order
removing V/HStack changing by orientation <- this one removes stutter!
reducing options from SectionH
divide SectionHs options into 2 VStack <- is applied to code above.
I'm new to Swift and SwiftUI, I don't know why this happens and can't get any clues to solve this problem.
thanks in advice.
UPDATE
removed SectionH, not fixed.
removed OtherView, not fixed.
I think theres a clue on if state with orientation.

How to pass selected struct to another view?

I'm struggling to pass the right data to another View.
The idea is first to select the Task that has Status 0 and pass it to CardContentView to display under the Section of New tasks. If I print the values, its correct but it always displays the first data/array regardless of its Status. What could be done here?
struct Tasks: Identifiable {
let id = UUID()
let name: String
let status: Int
let image: String
}
extension Tasks {
static var testData: [Tasks] {
return [
Tasks(name: "Inprogress", status: 1, image:"a1"),
Tasks(name: "New", status: 0, image:"a2"),
]
}
}
ContentsView
struct ContentsView: View {
#State var items: [Tasks]
var size = 0
var body: some View {
NavigationView {
List {
let new = items.filter({$0.status == 0})
let size = new.count
if size > 0 {
Section(header:Text("\(size)" + " New")){
//let _ = print(new)
ForEach(new.indices, id: \.self) {itemIndex in
NavigationLink(destination: ChosenTask()) {
CardContentView(item: self.$items[itemIndex])
}
}
}
}
}
.navigationBarTitle("My tasks")
}
}
}
CardContentView
struct CardContentView: View {
#Binding var item: Tasks
var body: some View {
HStack {
VStack(alignment: .leading,spacing: 5) {
Label("Name: " + (item.name), systemImage: "person.crop.circle")
.font(.system(size: 12))
.labelStyle(.titleAndIcon)
}
.frame(maxWidth: .infinity, alignment: .leading)
Image(item.image)
.resizable()
.frame(width: 60, height: 70)
}
}
}
You are already passing the item to another view when you call CardContentView. You just have to do the same thing and pass the item to ChosenTask in your NavigationLink. When the user taps the item, SwiftUI will take care of creating and displaying the ChoseTask view for you.
You should also avoid using indices. There is no need. Your struct conforms to Identifiable so you can use it directly
var body: some View {
NavigationView {
List {
let new = items.filter({$0.status == 0})
if !new.isEmpty {
Section(header:Text("\(size)" + " New")){
//let _ = print(new)
ForEach(new) {item in
NavigationLink(destination: ChosenTask(item: item)) {
CardContentView(item: item)
}
}
}
}
}
.navigationBarTitle("My tasks")
}
}

SwiftUI DisclosureGroup Expand each section individually

I'm using a Foreach and a DisclosureGroup to show data.
Each section can Expand/Collapse.
However they all are Expanding/Collapsing at the same time.
How do I Expand/Collapse each section individually?
struct TasksTabView: View {
#State private var expanded: Bool = false
var body: some View {
ForEach(Array(self.dict!.keys.sorted()), id: \.self) { key in
if let tasks = self.dict![key] {
DisclosureGroup(isExpanded: $expanded) {
ForEach(Array(tasks.enumerated()), id:\.1.title) { (index, task) in
VStack(alignment: .leading, spacing: 40) {
PillForRow(index: index, task: task)
.padding(.bottom, 40)
}.onTapGesture {
self.selectedTask = task
}
}
} label: {
Header(title: key, SubtitleText: Text(""), showTag: true, tagValue: tasks.count)
}.accentColor(.rhinoRed)
}
}
}
}
You could have a Set containing the keys of all the expanded sections. If a section is expanded, add it to the set. It is then removed when it is collapsed.
Code:
#State private var expanded: Set<String> = []
DisclosureGroup(
isExpanded: Binding<Bool>(
get: { expanded.contains(key) },
set: { isExpanding in
if isExpanding {
expanded.insert(key)
} else {
expanded.remove(key)
}
}
)
) {
/* ... */
}
It’s not working because the expanded flag links the DiscolureGroup all together. DisclosureGroup is smart enough to expand/collapse each item individually (see below demo).
struct ContentView: View {
struct Task: Identifiable, Hashable {
let id: UUID = UUID()
let name: String = "Task"
}
let allTasks: [[Task]] = [
[Task(), Task()],
[Task()],
[Task(), Task(), Task()]
]
var body: some View {
VStack {
ForEach(allTasks.indices, id: \.self) { indice in
DisclosureGroup() {
ForEach(allTasks[indice]) { task in
Text(task.name)
}
} label: {
Text("Tasks \(indice)")
}
}
}
}
}
However it seems that OutlineGroup is a perfect fit to your use case:
struct Task<Value: Hashable>: Hashable {
let value: Value
var subTasks: [Task]? = nil
}
List(allTasks, id: \.value, children: \.subTasks) { tree in
Text(tree.value).font(.subheadline)
}.listStyle(SidebarListStyle())

SwiftUI: How to select multi items(image) with ForEach?

I'm working on my project with the feature of select multiple blocks of thumbnails. Only selected thumbnail(s)/image will be highlighted.
For the ChildView, The binding activeBlock should be turned true/false if a use taps on the image.
However, when I select a thumbnail, all thumbnails will be highlighted.I have come up with some ideas like
#State var selectedBlocks:[Bool]
// which should contain wether or not a certain block is selected.
But I don't know how to implement it.
Here are my codes:
ChildView
#Binding var activeBlock:Bool
var thumbnail: String
var body: some View {
VStack {
ZStack {
Image(thumbnail)
.resizable()
.frame(width: 80, height: 80)
.background(Color.black)
.cornerRadius(10)
if activeBlock {
RoundedRectangle(cornerRadius: 10)
.stroke(style: StrokeStyle(lineWidth: 2))
.frame(width: 80, height: 80)
.foregroundColor(Color("orange"))
}
}
}
BlockBView
struct VideoData: Identifiable{
var id = UUID()
var thumbnails: String
}
struct BlockView: View {
var videos:[VideoData] = [
VideoData(thumbnails: "test"), VideoData(thumbnails: "test2"), VideoData(thumbnails: "test1")
]
#State var activeBlock = false
var body: some View {
ScrollView(.horizontal){
HStack {
ForEach(0..<videos.count) { _ in
Button(action: {
self.activeBlock.toggle()
}, label: {
ChildView(activeBlock: $activeBlock, thumbnail: "test")
})
}
}
}
}
Thank you for your help!
Here is a demo of possible approach - we initialize array of Bool by videos count and pass activated flag by index into child view.
Tested with Xcode 12.1 / iOS 14.1 (with some replicated code)
struct BlockView: View {
var videos:[VideoData] = [
VideoData(thumbnails: "flag-1"), VideoData(thumbnails: "flag-2"), VideoData(thumbnails: "flag-3")
]
#State private var activeBlocks: [Bool] // << declare
init() {
// initialize state with needed count of bools
self._activeBlocks = State(initialValue: Array(repeating: false, count: videos.count))
}
var body: some View {
ScrollView(.horizontal){
HStack {
ForEach(videos.indices, id: \.self) { i in
Button(action: {
self.activeBlocks[i].toggle() // << here !!
}, label: {
ChildView(activeBlock: activeBlocks[i], // << here !!
thumbnail: videos[i].thumbnails)
})
}
}
}
}
}
struct ChildView: View {
var activeBlock:Bool // << value, no binding needed
var thumbnail: String
var body: some View {
VStack {
ZStack {
Image(thumbnail)
.resizable()
.frame(width: 80, height: 80)
.background(Color.black)
.cornerRadius(10)
if activeBlock {
RoundedRectangle(cornerRadius: 10)
.stroke(style: StrokeStyle(lineWidth: 2))
.frame(width: 80, height: 80)
.foregroundColor(Color.orange)
}
}
}
}
}
Final result
Build your element and it's model first. I'm using MVVM,
class RowModel : ObservableObject, Identifiable {
#Published var isSelected = false
#Published var thumnailIcon: String
#Published var name: String
var id : String
var cancellables = Set<AnyCancellable>()
init(id: String, name: String, icon: String) {
self.id = id
self.name = name
self.thumnailIcon = icon
}
}
//Equivalent to your BlockView
struct Row : View {
#ObservedObject var model: RowModel
var body: some View {
GroupBox(label:
Label(model.name, systemImage: model.thumnailIcon)
.foregroundColor(model.isSelected ? Color.orange : .gray)
) {
HStack {
Capsule()
.fill(model.isSelected ? Color.orange : .gray)
.onTapGesture {
model.isSelected = !model.isSelected
}
//Two way binding
Toggle("", isOn: $model.isSelected)
}
}.animation(.spring())
}
}
Prepare data and handle action in your parent view
struct ContentView: View {
private let layout = [GridItem(.flexible()),GridItem(.flexible())]
#ObservedObject var model = ContentModel()
var body: some View {
VStack {
ScrollView {
LazyVGrid(columns: layout) {
ForEach(model.rowModels) { model in
Row(model: model)
}
}
}
if model.selected.count > 0 {
HStack {
Text(model.selected.joined(separator: ", "))
Spacer()
Button(action: {
model.clearSelection()
}, label: {
Text("Clear")
})
}
}
}
.padding()
.onAppear(perform: prepare)
}
func prepare() {
model.prepare()
}
}
class ContentModel: ObservableObject {
#Published var rowModels = [RowModel]()
//I'm handling by ID for futher use
//But you can convert to your Array of Boolean
#Published var selected = Set<String>()
func prepare() {
for i in 0..<20 {
let row = RowModel(id: "\(i)", name: "Block \(i)", icon: "heart.fill")
row.$isSelected
.removeDuplicates()
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] selected in
guard let `self` = self else { return }
print(selected)
if selected {
self.selected.insert(row.name)
}else{
self.selected.remove(row.name)
}
}).store(in: &row.cancellables)
rowModels.append(row)
}
}
func clearSelection() {
for r in rowModels {
r.isSelected = false
}
}
}
Don't forget to import Combine framework.

Resources