How to close Half sheet in this situation? - swiftui

I want to close the half sheet and back to the root view In swiftUI when with navigationLink we go to the another view. dismiss() doesn't work and turn us back to the previous view not the root view.
struct ContentView: View {
#State var showFirstSheetView = false
var body: some View {
NavigationView {
VStack {
Text("half sheet")
.onTapGesture {
showFirstSheetView.toggle()
}
}
.navigationTitle("Root view")
.sheet(isPresented: $showFirstSheetView) {
halfSheet()
}
}
}
}
struct halfSheet : View {
#State var showSecondView = false
var body: some View {
NavigationView {
VStack {
}
.background(
NavigationLink(isActive: $showSecondView, destination: {
SecondView()
}, label: {
EmptyView()
})
)
.navigationTitle("First view")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems( trailing: Button(action: {
showSecondView.toggle()
}) {
Text("Next")
}
)
}
}
}
struct SecondView : View {
#Environment(\.dismiss) var dismiss
var body: some View {
VStack {
}
.navigationTitle("Second view")
.navigationBarTitleDisplayMode(.inline)
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: Button(action: {
dismiss()
}) {
HStack(spacing : 5) {
Image(systemName: "chevron.backward")
Text("Back")
}
}, trailing: Button(action: {
// How back to the root View?
// below code works but not compatible with ios 15 and gives a warning
// UIApplication.shared.windows.first?.rootViewController?.dismiss(animated: true)
}) {
Text("Done")
})
}
}

Related

SwiftUI: two column NavigationView not loading details after rotation?

I have the following SwiftUI code:
struct ContentView: View {
var body: some View {
NavigationView {
Form {
Section {
NavigationLink {
DetailsView()
} label: {
Text("Show details")
}
}
}
Text("Select details")
}
}
}
struct DetailsView: View {
#State var showModal = false
var body: some View {
ZStack {
Color.gray.ignoresSafeArea()
VStack {
Spacer()
Button {
showModal.toggle()
} label: {
Text("Show modal")
.foregroundColor(.black)
.font(.system(size: 20, weight: .bold))
}
}
}
.fullScreenCover(isPresented: $showModal) {
MyModalView {
showModal = false
}
}
}
}
struct MyModalView: View {
var someAction:()->()
var body: some View {
ZStack {
Color.black.ignoresSafeArea()
Button {
someAction()
} label: {
Text("some action")
.foregroundColor(.white)
}
}
}
}
I am experiencing the following bug, where tapping on "Show details" won't show the DetailsView anymore after rotation...
How can I fix this?
Navigation view is really problematical but will be improved with IOS 16. Here is my solution
struct ContentView: View {
#State var navigate = false
var body: some View {
NavigationView {
Form {
Section {
NavigationLink(destination: DetailsView(navigate: $navigate), isActive: $navigate){
Text("Show details")
}
}
}
Text("Select details")
}
.navigationViewStyle(.automatic)
}
}
struct DetailsView: View {
#Binding var navigate: Bool
#State var showModal = false
var body: some View {
ZStack {
Color.gray.ignoresSafeArea()
VStack {
Spacer()
Button {
showModal.toggle()
} label: {
Text("Show modal")
.foregroundColor(.black)
.font(.system(size: 20, weight: .bold))
}
}
}
.fullScreenCover(isPresented: $showModal) {
MyModalView {
showModal = false
}
}
.onAppear(){
navigate = false
}
}}
struct MyModalView: View {
var someAction:()->()
var body: some View {
ZStack {
Color.black.ignoresSafeArea()
Button {
someAction()
} label: {
Text("some action")
.foregroundColor(.white)
}
}
}}

SwiftUI NavigationLink in the TitleBar pushes the view twice, a Button doing the same thing is not

This is annoying. The Edit button in the NavigationBar pushes the View twice. I made a test button which behaves correctly doing the same thing:
import SwiftUI
struct DetailListPage: View {
#Environment(\.presentationMode) var presentationMode
var listName: ListNames
// #State private var isEditDetailListPageShowing = false
#State private var selection: String? = nil
var body: some View {
Form {
Section(header: Text(listName.title ?? "")
.font(.title)
.padding()) {
Text(listName.listDetail ?? "Nothing is set yet!")
.multilineTextAlignment(.leading)
.padding()
.cornerRadius(12)
}
NavigationLink(destination: EditDetailListPage(listName: listName)) {
Button {
} label: {
Text("Edit Page")
}
}
}
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
self.presentationMode.wrappedValue.dismiss()
} label: {
Text("Cancel")
} .padding()
//Edit List Detail
}
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink(
destination: EditDetailListPage(listName: listName)) {
Text("Edit")
}
}
}
}
The Text("Edit") right above is pushing the view twice.
The Button above it acts correctly. Would like to use the navigationbaritem instead of the button.
Works well for me, on macos 11.4, xcode 12.5, target ios 14.5 and macCatalyst 11.3.
Probably some other code (or settings/system) that is causing the issue.
What system are you using? Show us the missing code and how you call the views. Let us know if the test code below does not work for you.
This is the test code I used:
#main
struct TestErrorApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct EditDetailListPage: View {
var listName: [String]
var body: some View {
Text("EditDetailListPage")
}
}
struct ContentView: View {
var body: some View {
NavigationView {
DetailListPage(listName: ["test var"])
}.navigationViewStyle(StackNavigationViewStyle())
}
}
struct DetailListPage: View {
#Environment(\.presentationMode) var presentationMode
var listName: [String]
// #State private var isEditDetailListPageShowing = false
#State private var selection: String? = nil
var body: some View {
Form {
Section(header: Text("header string")
.font(.title)
.padding()) {
Text("Nothing is set yet!")
.multilineTextAlignment(.leading)
.padding()
.cornerRadius(12)
}
NavigationLink(destination: EditDetailListPage(listName: listName)) {
Button {
} label: {
Text("Edit Page")
}
}
}
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
self.presentationMode.wrappedValue.dismiss()
} label: {
Text("Cancel")
} .padding()
//Edit List Detail
}
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink(
destination: EditDetailListPage(listName: listName)) {
Text("Edit")
}
}
}
}
}
struct ListFrontPage: View {
#Environment(\.presentationMode) var presentationMode
#Environment(\.managedObjectContext) var managedObjectContext
#State private var isAddNewListShowing = false
var listNames: FetchRequest<ListNames>
init() {
listNames = FetchRequest<ListNames>(entity: ListNames.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \ListNames.sort, ascending: true)], animation: .default)
}
var body: some View {
VStack {
List() {
Text("Accounts")
.frame(maxWidth: .infinity)
.font(.system(size: 30, weight: .heavy, design: .default))
ForEach (listNames.wrappedValue) { listName in
NavigationLink(destination: DetailListPage(listName: listName)) {
Text("\(listName.title ?? "")")
}
}
.onDelete(perform: deleteItems)
.onMove(perform: moveItem)
}
Spacer()
ZStack {
NavigationLink(destination: AddNewList()) {
Image(systemName: "plus.circle.fill").font(.system(size: 64))
}
}
}
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: Button {
self.presentationMode.wrappedValue.dismiss()
} label: {
Image(systemName: "chevron.backward")
Label("Back", image: "")
}, trailing: EditButton())
.navigationBarTitle(Text("Account Management"))
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { listNames.wrappedValue[$0] }.forEach(CoreDataHelper.sharedManager.deleteItems)
}
}
private func moveItem(from offsets: IndexSet, to destination: Int)
{
print("From: \(String(describing: offsets)) To: \(destination)")
// Make an array of items from fetched results
var revisedItems: [ ListNames ] = listNames.wrappedValue.map{ $0 }
// change the order of the items in the array
revisedItems.move(fromOffsets: offsets, toOffset: destination )
// update the userOrder attribute in revisedItems to
// persist the new order. This is done in reverse order
// to minimize changes to the indices.
for reverseIndex in stride( from: revisedItems.count - 1,
through: 0,
by: -1 )
{
revisedItems[ reverseIndex ].sort =
Int16( reverseIndex )
}
}
}

How to navigate between screens using a button in SwiftUI

Hello, I want to navigate between windows using a button but not use a NavigationLink. It looks ugly.
this is my code
import SwiftUI
struct ContentView: View {
var body: some View {
Button(action: action()){
Text("Hola")
.font(.largeTitle)
.frame(width: 100, height: 100)
.background(Color.red)
}
}
}
You can use an empty NavigationLink and bind your navigation flag or destination to your Button.
struct FirstView: View {
#State var navigationFlag = false
var body: some View {
NavigationView {
VStack {
Text("First View")
Button(action: {
self.navigationFlag = true
}, label: {
Text("navigate")
})
NavigationLink(destination: SecondView(),
isActive: self.$navigationFlag,
label: {
EmptyView()
})
}
}
}
}
struct SecondView: View {
var body: some View {
Text("Second View")
}
}

SwiftUI - Button Action to Alert and take action

I am trying to send alert based on a condition, but the Navigation link is executing regardless of the condition. I was hoping for an intercept.
Goal:
If condition is not me then do not launch new view
New View is launching and then alert.
I am sure my code is incorrect, but I am unsure how I should achieve this
Thanks in advance.
var body: some View {
NavigationView {
VStack {
Button(action: {}) {
//NavigationLink(destination: secondView()) {
NavigationLink(destination: checkState()) {
Text("Add to Cart")
}.padding()
.font(.system(size: 14))
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(6)
}
}
}.padding()
} // End of the GetOrder Struct
struct GetdOrderView_Previews: PreviewProvider {
static var previews: some View {
GetdOrderView()
}
}
}
struct checkState: View {
#ObservedObject var calcCheck = MealOrder()
#State var showingAlert = false
#State var myToggle = false
var body: some View {
NavigationView {
VStack {
Button(action: {
//Enter Action here
if self.myToggle == true {
self.showingAlert = true
} else {
self.showingAlert = true
}
}) {
Text("This is a test")
}.padding()
.font(.system(size: 14))
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(6)
//Insert Alerts
.alert(isPresented: $showingAlert) {
if self.myToggle {
return Alert(title: Text("Showing Message"), message: Text("Cart is valid"), dismissButton: .default(Text("OK")))
} else {
return Alert(title: Text("Showing Alert"), message: Text("Cart Empty"), dismissButton: .default(Text("Cancel")))
}
}
}
}
}
}
struct secondView: View {
var body: some View {
VStack {
Text("This is the second test")
}
}
}
Try the following approach
#State var activateLink = false
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: checkState(), isActive: $activateLink) {
EmptyView()
}
Button(action: {
if _YOUR_CONDITION_HERE_ {
self.activateLink = true
}
}) {
Text("Add to Cart")
.padding()
.font(.system(size: 14))
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(6)
}
}
.onAppear { self.activateLink = false }
}.padding()
}// End of the GetOrder Struct

SwiftUI ContextMenu navigation to another view

I am trying to get a context menu to navigate to another view using the following code
var body: some View
{
VStack
{
Text(self.event.name).font(.body)
...
Spacer()
NavigationLink(destination: EditView(event: self.event))
{
Image(systemName: "pencil")
}
}
.navigationBarTitle(Text(appName))
.contextMenu
{
NavigationLink(destination: EditView(event: self.event))
{
Image(systemName: "pencil")
}
}
}
The NavigationLink within the VStack works as expected and navigates to the edit view but I want to use a contextMenu. Although the context menu displays the image, when I tap on it it doesn't navigate to the edit view, instead it just cancels the context menu.
I am doing this within a watch app but don't think that should make a difference, is there anything special I have to do with context menu navigation?
I would use the isActive variant of NavigationLink that you can trigger by setting a state variable. Apple documents this here
This variant of NavigationLink is well fit for dynamic/programatic navigation.
Your .contextMenu sets the state variable to true and that activates the NavigationLink. Because you don't want the link to be visible, set the label view to EmptyView
Here's an example, not identical to your post but hopefully makes it clear.
struct ContentView: View {
#State private var showEditView = false
var body: some View {
NavigationView {
VStack {
Text("Long Press Me")
.contextMenu {
Button(action: {
self.showEditView = true
}, label: {
HStack {
Text("Edit")
Image(systemName: "pencil")
}
})
}
NavigationLink(destination: Text("Edit Mode View Here"), isActive: $showEditView) {
EmptyView()
}
}
.navigationBarTitle("Context Menu")
}
}
}
In Xcode 11.4 it's now possible to do this with sensible NavigationLink buttons. Yay! 🎉
.contextMenu {
NavigationLink(destination: VisitEditView(visit: visit)) {
Text("Edit visit")
Image(systemName: "square.and.pencil")
}
NavigationLink(destination: SegmentsEditView(timelineItem: visit)) {
Text("Edit individual segments")
Image(systemName: "ellipsis")
}
}
This works on Xcode 11.6
struct ContentView: View {
#State var isActiveFromContextMenu = false
var body: some View {
NavigationView{
VStack{
NavigationLink(destination : detailTwo(), isActive: $isActiveFromContextMenu ){
EmptyView()
}
List{
NavigationLink(destination: detail() ){
row(isActiveFromContextMenu: $isActiveFromContextMenu)
}
NavigationLink(destination: detail() ){
row(isActiveFromContextMenu: $isActiveFromContextMenu)
}
NavigationLink(destination: detail() ){
row(isActiveFromContextMenu: $isActiveFromContextMenu)
}
}
}
}
}
}
struct detail: View {
var body: some View{
Text("Detail view")
}
}
struct detailTwo: View {
var body: some View{
Text("DetailTwo view")
}
}
struct row: View {
#Binding var isActiveFromContextMenu : Bool
var body: some View {
HStack{
Text("item")
}.contextMenu{
Button(action: {
self.isActiveFromContextMenu = true
})
{
Text("navigate to")
}
}
}
}
I found success in masking the NavigationLink in the background and switching the context with a Button as the shortest yet simplest alternative.
struct ContentView: View {
#State private var isShowing = false
var body: some View {
NavigationView {
Text("Hello")
.background(NavigationLink("", destination: Text("World!"), isActive: $isShowing))
.contextMenu {
Button {
isShowing = true
} label: {
Label("Switch to New View", systemImage: "chevron.forward")
}
}
}
}
}