SwiftUI EditButton() bug - ios

I'm presenting a List inside a modal. If I'm inside a NavigationView the EditButton its totally broken.
struct ContentView: View {
#State var showSheetView = false
var body: some View {
NavigationView {
Button(action: {
self.showSheetView.toggle()
}) {
Image(systemName: "bell.circle.fill")
.font(Font.system(.title))
}
.sheet(isPresented: $showSheetView) {
SheetView()
}
}
}
}
struct SheetView: View {
#State private var myArray: [String] = ["One", "Two", "Three"]
var body: some View {
NavigationView {
VStack {
List {
ForEach(myArray, id: \.self) { item in
Text(item)
}.onDelete(perform: { indexSet in
})
}
}
.navigationBarItems(trailing: EditButton())
}
}
}
If I remove the NavigationView where i present from, then at first it seems to work, the second time i present it gets broken again.
struct ContentView: View {
#State var showSheetView = false
var body: some View {
Button(action: {
self.showSheetView.toggle()
}) {
Image(systemName: "bell.circle.fill")
.font(Font.system(.title))
}
.sheet(isPresented: $showSheetView) {
SheetView()
}
}
}

Manually handling the editMode works for me on macOS Big Sur with Xcode 12.1 / iOS 14.1.
I also had a problem of EditButton showing "Edit" again in an edit mode when I rotate the simulator, and the below solution solves it as well.
The following solution uses a custom EditButton struct that handles a manual editMode binding.
First the custom EditButton:
struct EditButton: View {
#Binding var editMode: EditMode
var body: some View {
Button {
switch editMode {
case .active: editMode = .inactive
case .inactive: editMode = .active
default: break
}
} label: {
if let isEditing = editMode.isEditing, isEditing {
Text("Done")
} else {
Text("Edit")
}
}
}
}
Using the above EditButton is straightforward:
struct SheetView: View {
#State private var myArray: [String] = ["One", "Two", "Three"]
#State private var editMode = EditMode.inactive
var body: some View {
NavigationView {
VStack {
List {
ForEach(myArray, id: \.self) { item in
Text(item)
}.onDelete(perform: { indexSet in
})
}
}
.navigationBarItems(trailing: EditButton(editMode: $editMode))
.environment(\.editMode, $editMode)
.animation(.spring(response: 0))
}
}
}
The EditButton in the trailing navigation bar item handles the #State private var editMode kept in SheetView.
This editMode is then injected into the inner views using the environment .environment(\.editMode, $editMode).
For the animation effect of the edit mode transition, I found .spring(response: 0) most appropriate.

Instead of
.navigationBarItems(trailing: EditButton())
you could try:
.toolbar { EditButton() }
I had the same problem and this worked fine for me.

This worked for me, in iOS 16.0
struct MyEditButton: View {
#Binding var editMode: EditMode
var body: some View {
Button {
switch editMode {
case .active: editMode = .inactive
case .inactive: editMode = .active
default: break
}
} label: {
if let isEditing = editMode.isEditing, isEditing {
Text("Done")
} else {
Text("Edit")
}
}
}
}
struct ContentView: View {
#State var editMode: EditMode = .inactive
#State var list = ["A", "B", "C"]
var body: some View {
Form {
Section(header: HStack {
MyEditButton(editMode: $editMode)
.frame(maxWidth: .infinity, alignment: .trailing)
.overlay(Text("LIST"), alignment: .leading)
}) {
List {
ForEach(list, id: \.self) { value in
Text(value)
}
.onDelete(perform: deleteSection)
.onMove(perform: moveSection)
}
}
}
.environment(\.editMode, $editMode)
.padding()
}
func deleteSection(at offsets: IndexSet) {
list.remove(atOffsets: offsets)
}
func moveSection(from source: IndexSet, to destination: Int) {
list.move(fromOffsets: source, toOffset: destination)
}
}

Related

Why does withAnimation not cause an animation?

I try to switch from one screen to another by pressing a button (see full code below). The switch from the first view to the second view (and vice versa) works, but no animation is taking place.
Why does this behavior happen?
Full code:
struct ContentView: View {
#AppStorage("firstViewActive") var isFirstViewActive: Bool = true
var body: some View {
if isFirstViewActive {
FirstView()
} else {
SecondView()
}
}
}
struct FirstView: View {
#AppStorage("firstViewActive") var isFirstViewActive: Bool = true
var body: some View {
ZStack {
Color(.red).ignoresSafeArea(.all, edges: .all)
VStack {
Spacer()
Text("This is the first view")
Spacer()
Button {
withAnimation {
isFirstViewActive = false
}
} label: {
Text("Go to second view")
}
Spacer()
}
}
}
}
struct SecondView: View {
#AppStorage("firstViewActive") var isFirstViewActive: Bool = false
var body: some View {
ZStack {
Color(.blue).ignoresSafeArea(.all, edges: .all)
VStack {
Spacer()
Text("This is the second view")
Spacer()
Button {
withAnimation {
isFirstViewActive = true
}
} label: {
Text("Go to first view")
}
Spacer()
}
}
}
}
The problem is with
#AppStorage("firstViewActive") var isFirstViewActive: Bool = true
If you change that to
#State var isFirstViewActive: Bool = true
and use #Binding in subviews, you will get the default animations.
In iOS 16, there seems to be a problem with #AppStorage vars and animation. But you can refer to this workaround

How can I go to a view by clicking on a Button in SwiftUI

If the user clicks on connexionBtnView I want to redirect them to an AdminView or UserView
import SwiftUI
struct ConnexionView: View {
#State var loginId: String = ""
#State var pwd: String = ""
#StateObject private var keyboardHander = KeyBoardHandler()
var body: some View {
NavigationView{
ZStack{
Image("background")
.ignoresSafeArea()
VStack (spacing: 15){
Spacer()
logoView
Spacer()
titleView
loginIdView
loginPwdView
connexionBtnView
Spacer()
NavigationLink {
LostPwdView()
} label: {
lostPwd
}
Spacer()
}.frame(maxHeight: .infinity)
.padding(.bottom,keyboardHander.keyboardHeight)
.animation(.default)
}
}
}
The NavigationLink has the isActive parameter. You can pass it in the init of NavigationLink and when this state variable has the true value you will redirect to another view. Details here.
struct ConnexionView: View {
#State var isActive: Bool = false
var body: some View {
NavigationView {
VStack {
NavigationLink(isActive: $isActive) {
LostPwdView()
} label: {
Text("Some Label")
}
Button("Tap me!") {
isActive = true
}
}
}
}
}
struct LostPwdView: View {
var body: some View {
Text("Hello")
}
}
What you need to do is having a #State variable that would trigger the navigation:
.fullScreenCover(
isPresented: $viewShown
) {
print("View dismissed")
} content: {
NextView()
}
Where NextView() is the View you want to show and the viewShown is your State variable, below a full example:
struct ExampleView: View {
#State var isNextPageOpen = false
var body: some View {
Button("Tap Here To Navigate") {
isNextPageOpen = true
}
.fullScreenCover(
isPresented: $isNextPageOpen
) {
print("View dismissed")
} content: {
NextView()
}
}
}

Presenting Sheet modally in SwiftUI

I am trying to present a modal sheet upon selecting the menu item in the navigation bar. But, the sheet is not displayed. Upon debugging I noticed that the state variable showSheet is not getting updated and I am sort of lost as to why it is not updating.
Any help is very much appreciated. Thank you!
There is another post (#State not updating in SwiftUI 2) that has a similar issue. Is this a bug in SwiftUI?
Below is a full sample
I have a fileprivate enum that defines two cases for the views - add and edit
fileprivate enum SheetView {
case add, edit
}
Below is the ContentView. The ContentView declares two #State variables that are set based on the menu item selected
The menu items (var actionItems) are on the NavigationView and has menu with 2 buttons - Add and Edit. Each button has an action set to toggle the showSheetView and the showSheet variables. The content is presented based on which item is selected. Content is built using #ViewBuilder
struct ContentView: View {
#State private var showSheetView = false
#State private var showSheet: SheetView? = nil
var body: some View {
GeometryReader { g in
NavigationView {
Text("Main Page")
.padding()
.navigationBarTitle("Main Page")
.navigationBarItems(trailing: actionItems)
}
}.sheet(isPresented: $showSheetView) {
content
}
}
var actionItems: some View {
Menu {
Button(action: {
showSheet = .add
showSheetView.toggle()
}) {
Label("Add Asset", systemImage: "plus")
}
Button(action: {
showSheet = .edit
showSheetView.toggle()
}) {
Label("Edit Asset", systemImage: "minus")
}
} label: {
Image(systemName: "dot.circle.and.cursorarrow").resizable()
}
}
#ViewBuilder
var content: some View {
if let currentView = showSheet {
switch currentView {
case .add:
AddAsset(showSheetView: $showSheetView)
case .edit:
EditAsset(showSheetView: $showSheetView)
}
}
}
}
Below are the two Views - AddAsset and EditAsset
struct AddAsset: View {
#Binding var showSheetView: Bool
var body: some View {
NavigationView {
Text("Add Asset")
.navigationBarTitle(Text("Add"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
print("Dismissing sheet view...")
self.showSheetView = false
}) {
Text("Done").bold()
})
}
}
}
struct EditAsset: View {
#Binding var showSheetView: Bool
var body: some View {
NavigationView {
Text("Edit Asset")
.navigationBarTitle(Text("Edit"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
print("Dismissing sheet view...")
self.showSheetView = false
}) {
Text("Done").bold()
})
}
}
}
The solution is to use sheet(item: variant.
Here is fixed code (there are many changes so all components included). Tested with Xcode 12.1 / iOS 14.1
enum SheetView: Identifiable {
var id: Self { self }
case add, edit
}
struct ContentView: View {
#State private var showSheet: SheetView? = nil
var body: some View {
GeometryReader { g in
NavigationView {
Text("Main Page")
.padding()
.navigationBarTitle("Main Page")
.navigationBarItems(trailing: actionItems)
}
}.sheet(item: $showSheet) { mode in
content(for: mode)
}
}
var actionItems: some View {
Menu {
Button(action: {
showSheet = .add
}) {
Label("Add Asset", systemImage: "plus")
}
Button(action: {
showSheet = .edit
}) {
Label("Edit Asset", systemImage: "minus")
}
} label: {
Image(systemName: "dot.circle.and.cursorarrow").resizable()
}
}
#ViewBuilder
func content(for mode: SheetView) -> some View {
switch mode {
case .add:
AddAsset(showSheet: $showSheet)
case .edit:
EditAsset(showSheet: $showSheet)
}
}
}
struct AddAsset: View {
#Binding var showSheet: SheetView?
var body: some View {
NavigationView {
Text("Add Asset")
.navigationBarTitle(Text("Add"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
print("Dismissing sheet view...")
self.showSheet = nil
}) {
Text("Done").bold()
})
}
}
}
struct EditAsset: View {
#Binding var showSheet: SheetView?
var body: some View {
NavigationView {
Text("Edit Asset")
.navigationBarTitle(Text("Edit"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
print("Dismissing sheet view...")
self.showSheet = nil
}) {
Text("Done").bold()
})
}
}
}

SwiftUI - View disappears if animated

I am building a custom segmented control. This is the code that I have written.
struct SegmentedControl: View {
private var items: [String] = ["One", "Two", "Three"]
#Namespace var animation:Namespace.ID
#State var selected: String = "One"
var body: some View {
ScrollView(.horizontal) {
HStack {
ForEach(items, id: \.self) { item in
Button(action: {
withAnimation(.spring()){
self.selected = item
}
}) {
Text(item)
.font(Font.subheadline.weight(.medium))
.foregroundColor(selected == item ? .white : .accentColor)
.padding(.horizontal, 25)
.padding(.vertical, 10)
.background(zStack(item: item))
}
}
} .padding()
}
}
private func zStack(item: String) -> some View {
ZStack{
if selected == item {
Color.accentColor
.clipShape(Capsule())
.matchedGeometryEffect(id: "Tab", in: animation)
} else {
Color(.gray)
.clipShape(Capsule())
}}
}
}
A control is Blue when it is selected.
It works as expected most of the time like in the following GIF.
However, sometimes if you navigate back and forth very fast, the Color.accentColor moves off screen and disappears as you see in the following GIF. I have used a lot of time but could not fix it.
Sometimes, I get this error.
Multiple inserted views in matched geometry group Pair<String,
ID>(first: "Tab", second: SwiftUI.Namespace.ID(id: 248)) have `isSource:
true`, results are undefined.
Info, It is easier to test it on a physical device rather than a simulator.
Update
This is my all codde including the ContentView and the Modal.
struct ContentView: View {
#State private var isPresented: Bool = false
var body: some View {
NavigationView {
VStack {
Button(action: {
self.isPresented.toggle()
}, label: {
Text("Button")
})
}
}
.sheet(isPresented: $isPresented, content: {
ModalView()
})
}
}
struct ModalView: View {
var body: some View {
NavigationView {
NavigationLink(
destination: TabbarView(),
label: {
Text("Navigate")
})
}
}
}
struct TabbarView: View {
private var items: [String] = ["One", "Two", "Three"]
#Namespace var animation:Namespace.ID
#State var selected: String = "" // change here
var body: some View {
ScrollView(.horizontal) {
HStack {
ForEach(items, id: \.self) { item in
Button(action: {
withAnimation{
self.selected = item
}
}) {
Text(item)
.font(Font.subheadline.weight(.medium))
.foregroundColor(selected == item ? .white : .accentColor)
.padding(.horizontal, 25)
.padding(.vertical, 10)
.background(zStack(item: item))
}
}
} .padding()
}
.onAppear { self.selected = "One" } // add this
}
private func zStack(item: String) -> some View {
ZStack{
if selected == item {
Color.accentColor
.clipShape(Capsule())
.matchedGeometryEffect(id: "Tab", in: animation)
} else {
Color(.gray)
.clipShape(Capsule())
}}
}
}

Dismissing a View using a "static nav bar"

I've created a simple view acting as a navbar which contains a menu button and some text. I'm using this as a top-level element outside my NavigationView which allows me to have the view static across all child pages that come into view. The reason I'm trying not to use the default navbar, with navbar items, is to avoid the dismissal/creation that you get along with the fading animation when you switch views.
The problem I'm now facing is dismissing the child view's when I have navigated away from the parent view. I'm able to update the button from a menu icon to a back icon, but the action of the button is not triggered. Been looking online to see if anyone has done something similar but had no luck, I'm not sure what I'm trying to achieve is even possible or whether I am going about it the right way. Is there anyway to call self.presentationMode.wrappedValue.dismiss() from the child views even though the header is initialised in the root view? Any help is appreciated, here's what I have so far:
Root View (View1):
struct View1: View {
#State var showMenuButton: Bool = false
var body: some View {
VStack {
CustomNavigationView(showMenuButton: self.showMenuButton)
NavigationView {
NavigationLink(destination: View2()) {
Text("View 2")
}
.navigationBarTitle("")
.navigationBarHidden(true)
.onDisappear(){
self.showMenuButton = false
}
.onAppear() {
self.showMenuButton = true
}
}
}
}
}
Child View of root view (View2):
struct View2: View {
var body: some View {
VStack{
Text("This is View 2")
.navigationBarTitle("")
.navigationBarHidden(true)
NavigationLink(destination: View3()) {
Text("View 3")
}
}
}
}
Child view of view 2 (View3):
struct View3: View {
var body: some View {
VStack{
Text("This is View 3")
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
Custom Navigation View:
struct CustomNavigationView: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var showMenuButton = false
var body: some View {
VStack {
HStack {
if showMenuButton {
Button(action: {
//Do Something
}) {
Image(systemName: "line.horizontal.3")
.foregroundColor(.black)
}
} else {
Button(action: { self.presentationMode.wrappedValue.dismiss()}) {
Image(systemName: "arrow.left")
.foregroundColor(.black)
}
}
Text("Sometext")
}
}
}
}
The environment object 'presentationMode' that you used inside the first view cannot dismiss the views you pushed. Every view that wants to be dismissed must have their own objects. The object inside the first view does not belong to any other pushed views. So, you need to create view model to manage this task.
Here is the example code. Hope that will help you solve your problem.
class NavigationObserver: ObservableObject {
private var views: [Int:Binding<PresentationMode>] = [:]
private var current: Int = 0
func popView() {
guard let view = views[current] else {
return
}
view.wrappedValue.dismiss()
views[current] = nil
current -= 1
}
func pushView(id: Int, newView: Binding<PresentationMode>) {
guard views[id] == nil else {
return
}
current += 1
views[id] = newView
}
}
struct ContentView: View {
#State var showMenuButton: Bool = false
#ObservedObject var observer = NavigationObserver()
var body: some View {
VStack {
CustomNavigationView(observer: self.observer, showMenuButton: self.showMenuButton)
NavigationView {
NavigationLink(destination: View2(observer: self.observer)) {
Text("View 2")
}
.navigationBarTitle("")
.navigationBarHidden(true)
.onDisappear(){
self.showMenuButton = false
}
.onAppear() {
self.showMenuButton = true
}
}
}
}}
struct View2: View {
#Environment(\.presentationMode) var presentationMode
#ObservedObject var observer: NavigationObserver
var body: some View {
VStack{
Text("This is View 2")
.navigationBarTitle("")
.navigationBarHidden(true)
NavigationLink(destination: View3(observer: self.observer)) {
Text("View 3")
}
}.onAppear {
self.observer.pushView(id: 1, newView: self.presentationMode)
}
}}
struct View3: View {
#Environment(\.presentationMode) var presentationMode
#ObservedObject var observer: NavigationObserver
var body: some View {
VStack{
Text("This is View 3")
.navigationBarTitle("")
.navigationBarHidden(true)
}.onAppear
{
self.observer.pushView(id: 2, newView: self.presentationMode)
}
}
}
struct CustomNavigationView: View {
#ObservedObject var observer: NavigationObserver
var showMenuButton = false
var body: some View {
VStack {
HStack {
if showMenuButton {
Button(action: {
//Do Something
}) {
Image(systemName: "line.horizontal.3")
.foregroundColor(.black)
}
} else {
Button(action: {
self.observer.popView()
}) {
Image(systemName: "arrow.left")
.foregroundColor(.black)
}
}
Text("Sometext")
}
}
}
}
Thanks, X_X

Resources