ForEach Loop in Swift for Buttons - swiftui

I want to use a ForEach loop to simplify the following code:
.toolbar {
ToolbarItem() {
Button {
}
label: {
Image(systemName: "magnifyingglass")
}
}
ToolbarItem() {
Button {
}
label: {
Image(systemName: "plus")
}
}
}
But it's not working. My approach only creates the "magnifyingglass" button.
My approach:
let toolbar = ["magnifyingglass", "plus"]
.toolbar {
ToolbarItem() {
ForEach(toolbar.indices) { index in
Button {
}
label: {
Image(systemName: toolbar[index])
}
}
}
}

you could try this:
struct ContentView: View {
let toolbar = ["magnifyingglass", "plus"]
var body: some View {
NavigationView {
Text("testing")
.toolbar {
ToolbarItem() {
HStack { // <--- here
ForEach(toolbar.indices) { index in
Button { }
label: { Image(systemName: toolbar[index]) }
}
}
}
}
}
}
}

import SwiftUI
struct ContentView: View {
let toolbar = ["magnifyingglass", "plus"]
var body: some View {
NavigationView {
Text("Toolbar")
.navigationTitle("")
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
ForEach(toolbar, id: \.self) { index in
Button {
} label: {
Image(systemName: ("\(index)"))
}
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

I suggest (not tested) to put the for loop outside of ToolbarItem() :
let toolbar = ["magnifyingglass", "plus"]
.toolbar {
ForEach(toolbar.indices) { index in
ToolbarItem() {
Button {
}
label: {
Image(systemName: toolbar[index])
}
}
}
}

Related

How to switch between tabBar and toolbar swiftUI?

In the files App after you pressed the Select button the tabBar switch to the toolbar.
How can I do this with swiftUI?(Switch between tabBar and toolbar)
struct tabBar: View {
var body: some View {
TabView {
ContentView().tabItem {
Image(systemName: "paperplane.fill")
Text("tabBar")
}
}
.toolbar {
ToolbarItem(placement: .bottomBar, content: {
Button(action: {
}){
Text("toolBar1")
}
})
ToolbarItem(placement: .bottomBar, content: {
Button() {
} label: {
Text("toolBar2")
}
})
}
}
}
For iOS 16 and above, you can use the toolbar(_:for:) method to toggle between visible and hidden states. Also, don't forget to wrap the view in a NavigationView, or else, setting the visibility of the bottom toolbar won't work.
import SwiftUI
struct ContentView: View {
#State var shouldShowTabBar = false
var body: some View {
NavigationView {
TabView {
Group {
Button("Switch Between Tab Bar and Toolbar") {
shouldShowTabBar.toggle()
}
.tabItem {
Label("Tab 1", systemImage: "list.dash")
}
Text("Tab 2")
.tabItem {
Label("Tab 2", systemImage: "square.and.pencil")
}
}
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button {
} label: {
Text("Toolbar Button")
}
}
}
.toolbar(shouldShowTabBar ? .visible : .hidden, for: .tabBar)
.toolbar(shouldShowTabBar ? .hidden : .visible, for: .bottomBar)
}
}
}
}
If you have to support iOS 14 and 15, you can check every item if it should be visible and hide/show them one by one.
import SwiftUI
struct ContentView: View {
#State var shouldShowTabBar = false
var body: some View {
NavigationView {
TabView {
Group {
Button("Switch Between Tab Bar and Toolbar") {
shouldShowTabBar.toggle()
}
.tabItem {
if shouldShowTabBar {
Label("Tab 1", systemImage: "list.dash")
}
}
Text("Tab 2")
.tabItem {
if shouldShowTabBar {
Label("Tab 2", systemImage: "square.and.pencil")
}
}
}
.toolbar {
ToolbarItem(placement: .bottomBar) {
if !shouldShowTabBar {
Button {
} label: {
Text("Toolbar Button")
}
}
}
}
}
}
}
}

How to avoid the .searchable from appearing and disappearing?

I am having a lot of buggy behavior on .searchable, on iOS 16.1 (Xcode 14.1). As you can see in the screenshot below. When entering a view with a .searchable component it will overlap with the view in transition and then disappears.
I am trying to make the code as basic as possible.
struct ContentView: View {
var body: some View {
NavigationStack {
List {
NavigationLink {
Mailbox().navigationTitle("Inkomend")
} label: { Label("Inkomend", systemImage: "tray") }
NavigationLink {
Mailbox().navigationTitle("Verstuurd")
} label: { Label("Verstuurd", systemImage: "paperplane") }
NavigationLink {
Mailbox().navigationTitle("Prullenmand")
} label: { Label("Prullenmand", systemImage: "trash") }
}
.navigationTitle("Postbussen")
.refreshable {}
}
}
}
struct Mailbox: View {
#State private var searchQuery: String = ""
var body: some View {
List {
NavigationLink {
Text("Detail")
} label: {
VStack(alignment: .leading) {
Text("Apple").font(.headline)
Text("Verify your account.")
Text("Fijn dat je deze belangrijke stap neemt om je account te verifiëren.").lineLimit(2).foregroundColor(.secondary)
}
}
}
.searchable(text: $searchQuery)
}
}
Use NavigationView instead of NavigationStack.
Like Latin Bhuva said, the new NavigationStack is not intended to be used in this way, a NavigationView would be more correct in this case.
struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink {
Mailbox().navigationTitle("Inkomend")
} label: { Label("Inkomend", systemImage: "tray") }
NavigationLink {
Mailbox().navigationTitle("Verstuurd")
} label: { Label("Verstuurd", systemImage: "paperplane") }
NavigationLink {
Mailbox().navigationTitle("Prullenmand")
} label: { Label("Prullenmand", systemImage: "trash") }
}
.navigationTitle("Postbussen")
.refreshable {}
}
}
}

Unable to use custom alignment with non-sibling views with animation

Goal: to have the tapped person in the ScrollView/HStack align it's centre with the other views using the explicit custom alignment, CentreScreenAlignment
Problem: currently nothing is happening when I tap on a given person.
Code:
extension HorizontalAlignment {
private enum CentreScreenAlignment: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
d[HorizontalAlignment.center]
}
}
static let centreScreenAlignment = HorizontalAlignment(CentreScreenAlignment.self)
}
struct ContentView: View {
#State private var centrePt: Int = 0
var body: some View {
GeometryReader { g in
VStack(alignment: .centreScreenAlignment) {
ZStack {
HStack {
Button("Cancel") {
// action
}
.padding(.leading)
Spacer()
Button("Done") {
// action
}
.padding(.trailing)
}
Button {
// action
} label: {
Image(systemName: "person.fill.badge.plus")
.coordinateSpace(name: "Add button")
.foregroundColor(.blue)
.alignmentGuide(.centreScreenAlignment) { d in
d[.centreScreenAlignment]
}
}
}
EmptyView()
.alignmentGuide(.centreScreenAlignment) { d in
d[.centreScreenAlignment]
}
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(1..<10) { index in
Group {
if index == self.centrePt {
Button("Patient #\(index)") {
//
}.transition(AnyTransition.identity)
.alignmentGuide(.centreScreenAlignment) { d in
d[.centreScreenAlignment]
}
} else {
Button("Person #\(index)") {
withAnimation {
centrePt = index
print(centrePt)
}
}
.transition(AnyTransition.identity)
}
}
}
}
}.padding()
Text("Hello")
}
}
}
}
Thanks very much.

.confirmationDialog inside of .swipeActions does not work, iOS 15

With regards to iOS 15, Xcode 13; I am wondering if this is a bug, not properly implemented, or a planned non-functional feature...
With a list that has a .swipeActions that calls a .confirmationDialog the confirmation dialog does not show.
See example:
import SwiftUI
struct ContentView: View {
#State private var confirmDelete = false
var body: some View {
NavigationView {
List{
ForEach(1..<10) {_ in
Cell()
}
.swipeActions(edge: .trailing) {
Button(role: .destructive) {
confirmDelete.toggle()
} label: {
Label("Delete", systemImage: "trash")
}
.confirmationDialog("Remove this?", isPresented: $confirmDelete) {
Button(role: .destructive) {
print("Removed!")
} label: {
Text("Yes, Remove this")
}
}
}
}
}
}
}
struct Cell: View {
var body: some View {
Text("Hello")
.padding()
}
}
Misconfiguration:
The view modifier .confirmationDialog needs to be added to the view that is outside of the .swipeActions view modifier. It works when configured properly as shown below:
import SwiftUI
struct ContentView: View {
#State private var confirmDelete = false
var body: some View {
NavigationView {
List{
ForEach(1..<10) {_ in
Cell()
}
.swipeActions(edge: .trailing) {
Button(role: .destructive) {
confirmDelete.toggle()
} label: {
Label("Delete", systemImage: "trash")
}
}
//move outside the scope of the .swipeActions view modifier:
.confirmationDialog("Remove this?", isPresented: $confirmDelete) {
Button(role: .destructive) {
print("Removed!")
} label: {
Text("Yes, Remove this")
}
}
}
}
}
}
struct Cell: View {
var body: some View {
Text("Hello")
.padding()
}
}

SwiftUI: How to show some toolbar buttons only for iPhone

I have a set of toolbar buttons that should be presented only if the device is iPhone (not iPad).
The following code fails with this error:
Closure containing control flow statement cannot be used with result builder 'ToolbarContentBuilder'
I do understand why it fails, but I am not be able to come up with a solution, which achieves what I need.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink(
destination: Hello(),
label: {
Text("Hello")
})
}
}
}
}
struct Hello: View {
var body: some View {
Text("Hello World")
.toolbar() {
if UIDevice.current.userInterfaceIdiom == .phone {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
// do something
}, label: {
Text("Button1")
})
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
// do something
}, label: {
Text("Button2")
})
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
// do something
}, label: {
Text("Button3")
})
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I'm happy to create a separate function to achieve it. I simply can't figure out how to do it.
Probably you wanted this
struct Hello: View {
var body: some View {
Text("Hello World")
.toolbar() {
ToolbarItemGroup(placement: .navigationBarTrailing) {
if UIDevice.current.userInterfaceIdiom == .phone {
Button(action: {
// do something
}, label: {
Text("Button1")
})
Button(action: {
// do something
}, label: {
Text("Button2")
})
}
Button(action: {
// do something
}, label: {
Text("Button3")
})
}
}
}
}