How do I create a transition between from Login View to Tab View in SwiftUI? - ios

Here's the snippet of code from LoginView:
Button(action: {
if loginAndPasswordAreOK() {
// Perform Segue to TabView
} else {
self.isValidLoginAndPassword = false
self.email = ""
self.password = ""
}
}, label: {
and there's a piece of code of MainTabView (aka Home Tab):
struct MainTabView: View {
var body: some View {
TabView {
Text("Home Tab")
.font(.system(size: 30, weight: .bold, design: .rounded))
.tabItem {
Image(systemName: "house.fill")
Text("Home")
}
I googled around and saw NavigationLink or something but I don't want to wrap up this transition to a NavController at all.

Here:
import SwiftUI
struct ContentView: View {
#State var isPassOk: Bool = false
var userPass: String = "1234"
#State var userGivenPass: String = ""
var body: some View {
if isPassOk == false
{
HStack
{
TextField("Enter your Pass Here!", text: $userGivenPass)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button("Log in") {
// do your logig Here!
if userGivenPass == userPass
{
withAnimation(.easeInOut)
{
isPassOk = true
}
}
else
{
isPassOk = false
}
}
}
.font(Font.title)
.padding()
}
else if isPassOk == true
{
TabView {
Text("Home Tab")
.font(.system(size: 30, weight: .bold, design: .rounded))
.tabItem {
Image(systemName: "house.fill")
Text("Home")
}
}
}
}
}
Here Updated for you:
import SwiftUI
struct ContentView: View {
#State var isPassOk: Bool = false
var body: some View {
if isPassOk == false
{
LogInView(isPassOk: $isPassOk)
}
else if isPassOk == true
{
MainTabView()
}
}
}
struct LogInView: View {
#Binding var isPassOk: Bool
var userPass: String = "1234"
#State var userGivenPass: String = ""
var body: some View {
HStack
{
TextField("Enter your Pass Here!", text: $userGivenPass)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button("Log in") {
// do your logig Here!
if userGivenPass == userPass
{
withAnimation(.easeInOut)
{
isPassOk = true
}
}
else
{
isPassOk = false
}
}
}
.font(Font.title)
.padding()
}
}
struct MainTabView: View {
var body: some View {
TabView {
Text("Home Tab")
.font(.system(size: 30, weight: .bold, design: .rounded))
.tabItem {
Image(systemName: "house.fill")
Text("Home")
}
}
}
}

Related

Animation not working inside sheet for swiftui

I am using a sheet to present a list of options and on click of the option I want to change the view with the animation of sliding from trailing. As per my understanding and what I have read on various sites I have written this code but I am not sure why it is not working the way intended. I just want to know where exactly this code went wrong.
struct XYZ: App {
let persistenceController = PersistenceController.shared
#State var isPresented : Bool = false
#State var isSwiped : Bool = false
var body: some Scene {
WindowGroup {
optionList(isPresented: $isPresented)
.sheet(isPresented: $isPresented, content: {
Text("This is from modal view!")
.onTapGesture {
withAnimation(Animation.easeIn(duration: 10)){
isSwiped.toggle()
}
}
if isSwiped {
checkedList()
.transition(.move(edge: .trailing))
}
})
}
}
}
struct optionList : View {
#Binding var isPresented : Bool
var body: some View {
Text("This is a testView")
.onTapGesture {
withAnimation{
isPresented.toggle()
}
}
}
}
struct checkedList : View {
#State var name : String = "WatchList"
var arr = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh"]
#State var mp : [Int:Int] = [:]
var body: some View {
VStack{
HStack{
TextField("WatchlistName", text: $name)
.padding(.all)
Image(systemName: "trash.fill")
.padding(.all)
.onTapGesture {
print("Delete watchList!!")
}
}
ScrollView{
ForEach(arr.indices) { item in
HStack (spacing: 0) {
Image(systemName: mp.keys.contains(item) ? "checkmark.square" : "square")
.padding(.horizontal)
Text(arr[item])
}
.padding(.bottom)
.frame(width: UIScreen.main.bounds.width, alignment: .leading)
.onTapGesture {
if mp.keys.contains(item) {
mp[item] = nil
} else {
mp[item] = 1
}
}
}
}
Button {
print("Remove Ticked Elements!")
deleteWatchListItem(arr: Array(mp.keys))
} label: {
Text("Save")
}
}
}
func deleteWatchList(ind: Int){
print(ind)
}
func deleteWatchListItem(arr : [Int]) {
print(arr)
}
}
I tried to create a view and with the animation using withanimation with a bool variable tried to change the view.
It sounds like what you want is to push the checkedList on to a NavigationStack…
struct ContentView: View {
#State var isPresented : Bool = false
var body: some View {
Text("This is a testView")
.onTapGesture {
isPresented.toggle()
}
.sheet(isPresented: $isPresented, content: {
NavigationStack {
NavigationLink("This is from modal view!") {
checkedList()
}
}
})
}
}

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.

SwiftUI - Present 3 different Views with different parameter

I need to present 3 different Views.
AddListView
ChangeColor
EditListView
They take different paramater. AddListView does not have parameter while ChangeColor and EditListView takes Color and NSManagedObject respectively. However for the sake of simplicity, EditListView's paramter is integer in this example.
I am using .fullScreenCover(item: <#T##Binding<Identifiable?>#>, content: <#T##(Identifiable) -> View#>) for presenting them.
.fullScreenCover(item: $presentedViewType) { type in
if type == .AddListView {
AddListView()
}
else if type == .EditListView {
if let index = selectedIndex {
EditListView(index: index)
}
}
else if type == .ChangeColor {
if let color = selectedColor {
ColorView(color: color)
}
}
}
selectedIndex and selectedColor is nil even though I initialize them before initializing presentedViewType. And hence, an EmptyView is presented.
This is the project.
enum PresentedViewType: Identifiable {
case AddListView
case ChangeColor
case EditListView
var id: Int {
return hashValue
}
}
struct ContentView: View {
#State var presentedViewType: PresentedViewType?
#State var selectedColor: Color?
#State var selectedIndex: Int?
var body: some View {
NavigationView {
List {
Section {
NavigationLink(destination: Text("All")) {
Text("All")
}
.background(Color.blue)
.contextMenu {
Button(action: {
selectedColor = .blue
presentedViewType = .ChangeColor
}) {
Label("Change Color", systemImage: "paintbrush.pointed.fill")
}
}
}
ForEach(0..<10) { index in
NavigationLink(destination: Text("Row Details \(index)")) {
Text("Row \(index)")
}
.contextMenu {
Button(action: {
selectedIndex = index
presentedViewType = .EditListView
}) {
Label("Edit", systemImage: "square.and.pencil")
}
}
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
presentedViewType = .AddListView
}) {
Label("Add", systemImage: "plus")
}
}
}
.fullScreenCover(item: $presentedViewType) { type in
if type == .AddListView {
AddListView()
}
else if type == .EditListView {
if let index = selectedIndex {
EditListView(index: index)
}
}
else if type == .ChangeColor {
if let color = selectedColor {
ColorView(color: color)
}
}
}
}
}
}
struct ColorView: View {
#Environment(\.presentationMode) var presentationMode
#State var color: Color
var body: some View {
NavigationView {
Text("Color View")
.background(color)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "xmark")
}
}
}
}
}
}
}
struct AddListView: View {
#Environment(\.presentationMode) var presentationMode
#State var text: String = ""
var body: some View {
NavigationView {
TextField("", text: $text)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "xmark")
}
}
}
}
}
}
}
struct EditListView: View {
#Environment(\.presentationMode) var presentationMode
#State var index: Int
var body: some View {
NavigationView {
Text("Row \(index)")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "xmark")
}
}
}
}
}
}
}
I have to mention that they do not have fixed value. They have different value depending on which row you need to edit.
How to pass selectedIndex and selectedColor to EditListView and ColorView respectively?
Update
EditListView takes only selectedIndex while ColorView takes only selectedColor
You need to have #Binding properties inside EditListView and ColorView
struct EditListView: View {
#Binding var selectedIndex: Int?
// rest of view implementation
}
struct ColorView: View {
#Binding var selectedIndex: Int?
// rest of view implementation
}
and then pass the binding in the initialisers
.fullScreenCover(item: $presentedViewType) { type in
if type == .AddListView {
AddListView()
} else if type == .EditListView {
EditListView(index: $selectedIndex)
} else if type == .ChangeColor {
ColorView(color: $selectedColor)
}
}

SwiftUI open another view on button click

Am trying to navigate to another view page. I tried many methods but none worked. If there is a way to navigate to another page without navigationtool... then it will be much help full
struct ContentView: View {
#State var fname: String = ""
#State var lname: String = ""
#State var num: String = ""
#State var pass: String = ""
#State private var registerionAlert = false
#State private var registerionAlertActive: ActiveAlert = .success
var body: some View {
VStack(alignment: .center) {
Form {
Text("Registeration Form")
.font(.title)
.fontWeight(.bold)
.foregroundColor(Color.blue)
.multilineTextAlignment(.center)
.padding(.leading, 25.0)
TextField("Enter your first name...", text: $fname)
.padding()
.border(/*#START_MENU_TOKEN#*/Color.blue/*#END_MENU_TOKEN#*/, width: /*#START_MENU_TOKEN#*/1/*#END_MENU_TOKEN#*/)
TextField("Enter your last name...", text: $lname)
.padding()
.border(/*#START_MENU_TOKEN#*/Color.blue/*#END_MENU_TOKEN#*/, width: /*#START_MENU_TOKEN#*/1/*#END_MENU_TOKEN#*/)
TextField("Enter your phone number...", text: $num)
.padding()
.border(/*#START_MENU_TOKEN#*/Color.blue/*#END_MENU_TOKEN#*/, width: /*#START_MENU_TOKEN#*/1/*#END_MENU_TOKEN#*/)
TextField("Enter a password...", text: $pass)
.padding()
.border(/*#START_MENU_TOKEN#*/Color.blue/*#END_MENU_TOKEN#*/, width: /*#START_MENU_TOKEN#*/1/*#END_MENU_TOKEN#*/)
Button(action: {
self.registerTapped()
}) {
Text("Register")
.multilineTextAlignment(.center)
}
.padding(0.0)
.frame(width: 150.0, height: 30.0)
.background(/*#START_MENU_TOKEN#*/Color.green/*#END_MENU_TOKEN#*/)
.accentColor(/*#START_MENU_TOKEN#*/.white/*#END_MENU_TOKEN#*/)
.cornerRadius(/*#START_MENU_TOKEN#*/5.0/*#END_MENU_TOKEN#*/)
.offset(x: 95.0, y: /*#START_MENU_TOKEN#*/0.0/*#END_MENU_TOKEN#*/)
.alert(isPresented: $registerionAlert){
switch registerionAlertActive {
case .success:
return Alert(
title: Text("Register"),
message: Text("Registered Successfully"),
dismissButton: .default(
Text("Got it!"),
action: {
loginView()
print("success")
}
)
)
case .failed:
return Alert(
title: Text("Register"),
message: Text("Registered Unsuccessful, Try again later."),
dismissButton: .default(
Text("Got it!"))
)
}
}
}
.padding(10.0)
.background(/*#START_MENU_TOKEN#*/Color.blue/*#END_MENU_TOKEN#*/)
}
.padding()
.background(/*#START_MENU_TOKEN#*/Color.orange/*#END_MENU_TOKEN#*/)
}
func registerTapped() {
let params: [String: Any] = [
"first_name": "\(fname)",
"last_name": "\(lname)",
"phone": "\(num)",
"password": "\(pass)"
]
AF.request(
"http://192.168.0.9/mobile-api/public/register",
method: .post,
parameters: params,
encoding: JSONEncoding.default
).validate().responseString() {
response in
switch response.result {
case .success(_):
self.registerionAlertActive = .success
break
case .failure(_):
self.registerionAlertActive = .failed
break
}
self.registerionAlert = true
}
}
}
my another page is given below in which i haven't add much of things is only sample views
import SwiftUI
struct loginView: View {
var body: some View {
Text(/*#START_MENU_TOKEN#*/"Hello, World!"/*#END_MENU_TOKEN#*/)
}
}
struct loginView_Previews: PreviewProvider {
static var previews: some View {
loginView()
}
}
please help me navigate to another page
you can do this
struct ContentView: View {
#State var isOpen: Bool = false
var body: some View {
ZStack {
VStack {
Button(action: {
self.isOpen = true
}, label: {
Text("Tap me")
.foregroundColor(obj_saved_color.set_color)
}).sheet(isPresented: $isOpen, content: {
SecondView()
})
}
}
}}
struct SecondView: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Text("Second View")
}
}}

Resources