Aligning views in 2 different stacks using custom alignment guide in SwiftUI - layout

I have 2 HStacks sitting in one VStack as follows:
What I'm trying to achieve is to align the leading of Title 2 and Title 4 with each other. And also Title 1 and Title 3 to each other without using frames. Like the following:
Here is my code using HorizontalAlignment (I have also included the preview for convenience):
import SwiftUI
public struct ContentView: View {
public var body: some View {
VStack(alignment: .centerHorizontalAlignment, spacing: 10) {
HStack(alignment: .top, spacing: 16) {
VStack(alignment: .leading, spacing: 10) {
Text("Title 1")
.font(.body)
.fontWeight(.medium)
Text("123456789")
.font(.body)
.foregroundColor(.black.opacity(0.6))
}
.background(Color.green)
VStack(alignment: .leading, spacing: 10) {
Text("Title 2")
.font(.body)
.fontWeight(.medium)
Text("2 lines\nof text")
.font(.body)
.foregroundColor(.gray)
}
.background(Color.red)
.alignmentGuide(.centerHorizontalAlignment) { $0[HorizontalAlignment.leading] }
}
.padding()
.background(Color.purple)
HStack(alignment: .top, spacing: 16) {
VStack(alignment: .leading, spacing: 10) {
Text("Title 3")
.font(.body)
.fontWeight(.medium)
Text("Aaaaaaaaaa")
.font(.body)
.foregroundColor(.black.opacity(0.6))
Text("Bbbbbbbbbbbbbbbbbbbb")
.font(.body)
.foregroundColor(.black.opacity(0.6))
}
.background(Color.yellow)
VStack(alignment: .leading, spacing: 10) {
Text("Title 4")
.font(.body)
.fontWeight(.medium)
Text("Cccccccccccc")
.font(.body)
.foregroundColor(.black.opacity(0.6))
}
.background(Color.blue)
.alignmentGuide(.centerHorizontalAlignment) { $0[HorizontalAlignment.leading] }
}
.font(.body)
.padding()
.background(Color.gray)
}
.padding()
.frame(alignment: .leading)
.background(Color.cyan)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension HorizontalAlignment {
enum CenterHorizontalAlignment: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
d[HorizontalAlignment.center]
}
}
static let centerHorizontalAlignment = HorizontalAlignment(CenterHorizontalAlignment.self)
}
Would be appreciated if someone can give me some hints or solutions on how to achieve this.
I'm using Xcode 13.3.1 and Swift 5.
P.S. The text is fully generic and dynamic. So there is no guarantee that there are always 1 or 2 lines of text here. I would like this solution to be generic enough so it works no matter how long the content is.

Thanks to Paul B's answer:
public struct ContentView: View {
#State var title4Width: CGFloat = 0
#State var title2Width: CGFloat = 0
public var body: some View {
VStack( spacing: 10) {
HStack(alignment: .top, spacing: 16) {
VStack(alignment: .leading, spacing: 10) {
Text("Title 1")
.font(.body)
.fontWeight(.medium)
Text("123456789")
.font(.body)
.foregroundColor(.black.opacity(0.6))
}.background(Color.green)
Spacer()
VStack(alignment: .leading, spacing: 10) {
Text("Title 2")
.font(.body)
.fontWeight(.medium)
Text("2 lines\nof text")
.font(.body)
.foregroundColor(.gray)
}.background(Color.red)
.readSize { size in
title2Width = size.width
}.padding(.trailing, title4Width - title2Width > 0 ? (title4Width - title2Width): 0)
}.padding()
.background(Color.purple)
HStack(alignment: .top, spacing: 16) {
VStack(alignment: .leading, spacing: 10) {
Text("Title 3")
.font(.body)
.fontWeight(.medium)
Text("Aaaaaaaaaa")
.font(.body)
.foregroundColor(.black.opacity(0.6))
Text("Bbbbbbbbbbbbbbbbbbbb")
.font(.body)
.foregroundColor(.black.opacity(0.6))
}.background(Color.yellow)
Spacer()
VStack(alignment: .leading, spacing: 10) {
Text("Title 4")
.font(.body)
.fontWeight(.medium)
Text("Cccccccccccc")
.font(.body)
.foregroundColor(.black.opacity(0.6))
}.background(Color.blue)
.readSize { size in
title4Width = size.width
}.padding(.trailing, title2Width - title4Width > 0 ? (title2Width - title4Width): 0)
}.font(.body)
.padding()
.background(Color.gray)
}.padding()
.frame(alignment: .leading)
.background(Color.blue)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension View {
func readSize(onChange: #escaping (CGSize) -> Void) -> some View {
background(
GeometryReader { geometryProxy in
Color.clear
.preference(key: SizePreferenceKey.self, value: geometryProxy.size)
}
).onPreferenceChange(SizePreferenceKey.self, perform: onChange)
}
}
private struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

I think you want custom alignment guides: https://www.answertopia.com/swiftui/swiftui-stack-alignment-and-alignment-guides/

Related

Aligning Text within ZStack based on rotation in SwiftUI

I'm having some trouble aligning Text inside a ZStack...more specifically, if I rotate the device after I started the app...
I want the Text to be aligned to the top leading of the View, but below you can see images of what's happening...
If I open the app with the device in portrait, the alignment is correct...
Alignment with app started in portrait
...but if I rotate the device to landscape, the text moves to the top center...
Alignment after rotation to landscape
Same thing if I start the app with the device in landscape, all aligned correctly...
Alignment with app started in landscape
...but if I rotate the device to portrait, the text almost disappear completely...
Alignment after rotation to portrait
This is the code for the ContentView:
import SwiftUI
let furl = URL(fileURLWithPath: "path")
struct ContentView: View {
#State private var selected = 0
var body: some View {
TabView(selection: $selected) {
NavigationView {
HomeView()
}
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 0 ? "house.fill" : "house"))
Text("Home")
}.tag(0)
NavigationView {
CategoryView(dm: DownloadManager())
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 1 ? "text.justify" : "text.justify"))
Text("Categorie")
}.tag(1)
NavigationView {
GalleryView(dm: DownloadManager())
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 2 ? "photo.fill" : "photo"))
Text("Galleria")
}.tag(2)
NavigationView {
FavoritesView()
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 3 ? "star.fill" : "star"))
Text("Preferiti")
}.tag(3)
NavigationView {
InfoView()
}
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 4 ? "info.circle.fill" : "info.circle"))
Text("Informazioni")
}.tag(4)
}
.accentColor(.white)
.onAppear() {
UINavigationBar.appearance().barTintColor = UIColor(red: 112.0/255.0, green: 90.0/255.0, blue: 143.0/255.0, alpha: 1.0)
UITabBar.appearance().barTintColor = UIColor(red: 112.0/255.0, green: 90.0/255.0, blue: 143.0/255.0, alpha: 1.0)
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
This is the code for the HomeView (where I have the problem):
import SwiftUI
struct HomeView: View {
#State private var showAlertSheet = false
#ObservedObject var monitor = NetworkMonitor()
var body: some View {
ZStack {
Image("vivibusso_home")
.resizable()
.aspectRatio(contentMode: .fill)
.clipped()
VStack(alignment: .leading) {
Text("Benvenuto")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.leading)
Text("a Busso!")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.leading)
}
.frame(maxWidth: UIScreen.main.bounds.width, maxHeight: UIScreen.main.bounds.height, alignment: .topLeading)
.padding(.top)
}
.navigationTitle(Text("ViviBusso"))
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(trailing:
Button (action: {
self.showAlertSheet = true
}) {
Image(systemName: monitor.isConnected ? "wifi" : "wifi.slash")
})
.alert(isPresented: $showAlertSheet) {
if monitor.isConnected {
return Alert(title: Text("Tutto OK!"), message: Text("ViviBusso funziona correttamente!"), dismissButton: .default(Text("OK")))
}
return Alert(title: Text("Attenzione!"), message: Text("ViviBusso ha bisogno della connessione Internet per funzionare!"), dismissButton: .default(Text("OK")))
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
How can I solve this?
Thank you!
ZStack(alignment:.topLeading) { //<= here
GeometryReader { proxy in //<= here
Image("vivibusso_home")
.resizable()
.aspectRatio(contentMode: .fill)
.border(Color.black)
.frame(width: proxy.size.width, height: proxy.size.height)// <= here
}
VStack(alignment: .leading) {
Text("Benvenuto")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.leading)
Text("a Busso!")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.leading)
}
//<=here
.padding(.top)
}
.navigationTitle(Text("ViviBusso"))
...

UIView Top Point is Lower Then Expected

I have a format problem. How I want is the 2nd picture but for some reason, my view starts a little bit lower. You can see the gap between the pictures. I want to solve this problem without offset. Might be because of .navigationBarHidden(true) but I do not want navigation bar.
I added NavigationView to my code because I have a button down-right to add a new task.
Plus for some reason, this button is not clickable. Would be good if you give a hand to that problem.
import SwiftUI
struct TaskListView: View {
#State private(set) var data = ""
#State var isSettings: Bool = false
#State var isSaved: Bool = false
var body: some View {
NavigationView {
ZStack {
Color(#colorLiteral(red: 0.9333333333, green: 0.9450980392, blue: 0.9882352941, alpha: 1)).edgesIgnoringSafeArea(.all)
VStack {
TopBar()
HStack {
CustomTextField(data: $data, tFtext: "Find task", tFImage: "magnifyingglass")
Button(action: {
self.isSettings.toggle()
}, label: {
ZStack {
RoundedRectangle(cornerRadius: 15)
.frame(width: 50, height: 50, alignment: .center)
.foregroundColor(Color(#colorLiteral(red: 0.4274509804, green: 0.2196078431, blue: 1, alpha: 1)))
Image("buttonImage")
.resizable()
.frame(width: 30, height: 30, alignment: .center)
}
.padding(.horizontal, 15)
})
}
CustomSegmentedView()
ZStack {
TaskFrameView()
Button( action: {
self.isSaved.toggle()
}, label: {
ZStack {
RoundedRectangle(cornerRadius: 20)
.foregroundColor(Color(#colorLiteral(red: 1, green: 0.7137254902, blue: 0.2196078431, alpha: 1)))
Text("+")
.foregroundColor(.white)
.font(.title)
.fontWeight(.bold)
}
.frame(width: 40, height: 40)
.offset(x: 150, y: 220)
})
NavigationLink(
destination: NewTaskView(),
isActive: $isSaved,
label: {
Text("")
})
}
}
}
Spacer()
}
.navigationBarHidden(true)
}
}
struct TopBar: View {
var body: some View {
HStack {
Image("avatar")
.resizable()
.frame(width: 100, height: 100)
VStack(alignment: .leading){
DateView()
.font(Font.custom("SFCompactDisplay", size: 20))
.foregroundColor(.gray)
.padding(.vertical, 5)
Text("Hi, Random")
.font(Font.custom("SFCompactDisplay", size: 20))
}
Image(systemName: "ellipsis")
}
}
}
It is navigation view bar. The navigationBarHidden modifier should be inside NavigationView, like
}
.navigationBarHidden(true) // << here !!
Spacer()
} // end of NavigationView

Struggling with layout in SwiftUI on TVOS

I have a workable UI in TVOS using SwiftUI, but I can't figure out how to make it lay out properly.
Goals:
Screen is full screen, not inset in safe area
Album image is square, aspect ratio preserved, fills top-to-bottom
Album and artist text lays out comfortably, near the album art
import SwiftUI
struct ContentView: View {
#ObservedObject var ds = DataStore()
var body: some View {
HStack(alignment: .top) {
if (ds.currentRoom.albumImage != nil) {
Image(uiImage: ds.currentRoom.albumImage!)
.resizable()
.aspectRatio(contentMode: ContentMode.fit)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.black)
}
VStack(alignment: .leading, spacing: 8) {
Text(ds.currentRoom.artist ?? "?")
.font(.system(.title, design: .default))
.bold()
.foregroundColor(Color.gray)
.padding(.top, 100)
Text(ds.currentRoom.title ?? "?")
.font(.system(.headline, design: .default))
.foregroundColor(Color.gray)
.padding(.bottom, 100)
Button(action: { print ("pressed!" )} ) {
Image(systemName: "playpause")
.font(.system(.title, design: .default))
.foregroundColor(Color.gray)
.padding(30)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.green, lineWidth: 4)
)
}
}
}
.padding(20)
.background(Color.black)
.edgesIgnoringSafeArea(.all)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
In case it helps, here are the relevant helper and DataSource methods:
The DataStore() class has this method:
import SwiftUI
import Combine
class CurrentRoom {
var artist: String?
var title: String?
var album: String?
var albumArtURI: String?
var absoluteAlbumArtURI: String?
var albumImage: UIImage?
}
class DataStore: ObservableObject {
#Published var currentRoom: CurrentRoom = CurrentRoom()
init() {
getCurrentRoom()
}
func getCurrentRoom() {
currentRoom.artist = "Eilen Jewell"
currentRoom.album = "Sundown over Ghost Town"
currentRoom.title = "Half-Broke Horse"
currentRoom.absoluteAlbumArtURI = "https://images-na.ssl-images-amazon.com/images/I/71mkKfTQD0L._SX425_.jpg"
currentRoom.albumImage = Api().getImageDataFromURI(UrlAsString: currentRoom.absoluteAlbumArtURI)
}
}
struct DataStore_Previews: PreviewProvider {
static var previews: some View {
/*#START_MENU_TOKEN#*/Text("Hello, World!")/*#END_MENU_TOKEN#*/
}
}
Finally:
class Api {
func getImageDataFromURI(UrlAsString: String?) -> UIImage? {
if let URI = UrlAsString {
if URI.starts(with: "http") {
if let url = URL(string: URI) {
let data = try? Data(contentsOf: url)
if let imageData = data {
return UIImage(data: imageData)
}
}
}
}
return nil
}
}
Goal:
You can either go with Asperis answer, or, if ContentMode.Fit is important to you (as you don't want to clip the image), just remove the width part of the frame modifier at your Image, and then add a Spacer behind the VStack, which will consume the rest:
struct ContentView: View {
#ObservedObject var ds = DataStore()
var body: some View {
HStack(alignment: .top) {
if (ds.currentRoom.albumImage != nil) {
Image(uiImage: ds.currentRoom.albumImage!)
.resizable()
.aspectRatio(contentMode: ContentMode.fit)
.frame(minHeight: 0, maxHeight: .infinity)
.background(Color.black)
}
VStack(alignment: .leading, spacing: 8) {
Text(ds.currentRoom.artist ?? "?")
.font(.system(.title, design: .default))
.bold()
.foregroundColor(Color.gray)
.padding(.top, 100)
Text(ds.currentRoom.title ?? "?")
.font(.system(.headline, design: .default))
.foregroundColor(Color.gray)
.padding(.bottom, 100)
Button(action: { print ("pressed!" )} ) {
Image(systemName: "playpause")
.font(.system(.title, design: .default))
.foregroundColor(Color.gray)
.padding(30)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.green, lineWidth: 4)
)
}
}
.padding(.leading, 10)
Spacer()
}
.padding(20)
.background(Color.black)
.edgesIgnoringSafeArea(.all)
}
}
This will result in this image:
Correct layout

The keyboard of a TextField doesn't show when I tap it in SwiftUI

The keyboard of a TextField doesn't show when I tap it on a physical device and I don't know why, here is my code:
VStack {
HStack {
Image(colorScheme == .light ? "user" : "userDark")
.resizable()
.frame(width: 30, height: 30)
Text(localName)
.font(.system(size: 20))
Spacer()
}.padding(.horizontal)
ZStack {
HStack {
TextField("Change name", text: $name)
.textFieldStyle(PlainTextFieldStyle())
.padding(.leading, 5)
.font(.system(size: 20))
.autocapitalization(.none)
.disableAutocorrection(true)
.zIndex(1)
if self.name != "" {
Spacer()
Button(action: {
// update name
})
{
Text("Update")
.padding()
}.padding()
}
}.padding(.horizontal)
}
}
Thank you in advance!

SwiftUI - Unable to reference #Published value outside Struct

I am new to SwiftUI and am hoping for some assistance with a project I am developing.
I am unable to reference #published value outside a struct.
All values are correctly functioning within the struct using:
#ObservableObject
#Publihsed
#ObservedObject
I have a Struct within ContentView which is linked to another View where I would like to display Quantity and Costs.
I have attempted various ways to access the values as can be seen in the struct NewOrders, but I keep getting zero and not getting the updated value.
Am I missing a step or executing code incorrectly?
Thanks in advance
class MealOrders: ObservableObject {
//Jollof Rice - Published
#Published var jollof = 0
//Swallow - Published
#Published var swallow = 0
//Pepper Soup - Published
#Published var pepperSoup = 0
}
struct ContentView: View {
var body: some View {
VStack {
NavigationView {
Section {
VStack(alignment: .leading) {
NavigationLink(destination: MenuOption()) {
Text("Meal Options")
}
Spacer()
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight:
.infinity, alignment: .topLeading)
}.padding() //Vstack End
}
Section {
VStack {
Image("africanfoods")
.resizable()
.frame(width: 275.0, height: 250.0)
.clipShape(Circle())
.overlay(Circle().stroke(Color.black, lineWidth: 5))
.scaledToFit()
}
} //Section End
Section { //Social Media
VStack {
Spacer()
HStack {
Spacer()
Image("facebook")
.resizable()
.frame(width:40, height: 40)
.scaledToFit()
.padding()
Image("instergram")
.resizable()
.frame(width:40, height: 40)
.scaledToFit()
.padding()
Image("youtube")
.resizable()
.frame(width:40, height: 40)
.scaledToFit()
.padding()
Image("twitter")
.resizable()
.frame(width:40, height: 40)
.scaledToFit()
.padding(.horizontal, 50)
}
} //Vstack End
} //Social Media
.navigationBarTitle(Text("African Foods Center"))
} //NavView End
} //VStack End
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct MenuOption: View {
//Object Observed Declarations
#ObservedObject var meals = MealOrders()
//Meal Prices
#State private var jolloRiceUnitCost = 14.95 //Jollof Rice Unit Cost
#State private var swallowUnitCost = 12.50 //Swallow Unit Cost
#State private var pepperSoupUnitCost = 13.50 //Pepper Soup Unit Cost
#State private var deliveryCost = 5.99 //Delivery Cost
#State private var menuItem = 0
var menuItems = ["Rice Meals", "Swallow Meals", "Pepper Soups"]
//Meals Calculator
var calculateMeal: Double {
var orderCost = 0.0
//Jollof Rice
if menuItems[menuItem] == "Rice Meals" {
orderCost = self.jolloRiceUnitCost * Double(self.meals.jollof)
return orderCost
//Swallow - Pounded Yam / Eba
} else if menuItems[menuItem] == "Swallow Meals" {
orderCost = self.swallowUnitCost * Double(self.meals.swallow)
} else if menuItems[menuItem] == "Pepper Soups" {
orderCost = self.pepperSoupUnitCost * Double(self.meals.pepperSoup)
}
return orderCost
}
var body: some View {
VStack(alignment: .leading) {
Section(header: Text("Select Meal").padding(.horizontal, 25)) {
Picker("Select Item", selection: $menuItem) {
ForEach(0 ..< menuItems.count) {
Text(self.menuItems[$0])
}
}.pickerStyle(SegmentedPickerStyle())
.padding(.horizontal, 25)
if menuItems[menuItem] == "Rice Meals" {
Text("Rice Meals:")
.foregroundColor(.black)
.padding(.horizontal, 25)
Spacer().frame(height:20)
`Text("Rice meals consist of Jollof Rice, Rice and Stew, Fried
Rice. You can option in meat, fish and or plantain with any of the meals")`
.foregroundColor(.blue)
.lineLimit(nil)
.padding(.horizontal, 25)
Spacer().frame(height:60)
//Insert image - Jollof Rice
Image("jollofRice")
.resizable()
.frame(width:250, height: 250)
.scaledToFit()
.border(Color.black, width: 4)
.padding(.horizontal, 100)
Spacer().frame(height:20)
HStack {
Stepper("Quantity (Max 5)",value: $meals.jollof, in: 0...5)
.padding(.horizontal, 45)
Text("\(meals.jollof): £\(calculateMeal, specifier: "%.2f")")
.padding()
}.padding()
Section { //Button Order
VStack {//Add Stepper for Quantity
Spacer()
HStack(alignment: .center, spacing: 140) {
Spacer()
Button(action: {}) {
NavigationLink(destination: Text("Jollof:: \(meals.jollof), £\(calculateMeal, specifier: "%.2f")")) {
Text("Create Order")
.font(.system(size: 14))
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(6)
}.padding()
Spacer()
}
}
} //Vstack End
} //Button Section End
} else if menuItems[menuItem] == "Swallow Meals" {
Text("Swallow")
.foregroundColor(.green)
.padding(.horizontal, 25)
Spacer().frame(height:20)
`Text("Swallow is the colloqual word for Pounded Yam, Eba, Fufu or Amala. This is complemented with soups, such as Egusi, Okra etc. You could have this meal with either meat or fish")`
.foregroundColor(.blue)
.lineLimit(nil)
.padding(.horizontal, 25)
Spacer().frame(height:60)
//Inset Image
Image("poundedYamEgusi")
.resizable()
.frame(width:250, height:250)
.scaledToFit()
.border(Color.black, width: 4)
.padding(.horizontal, 100)
HStack {//Add Stepper for Quantity
Stepper("Quantity (Max 5)",value: $meals.swallow, in: 0...5)
.padding(.horizontal, 45)
Text("\(meals.swallow): £\(calculateMeal, specifier: "%.2f")")
.padding()
}.padding()
//Insert Order Button
Section {
VStack {
Spacer()
HStack(alignment: .center, spacing: 140) {
Spacer()
Button(action: {}) {
NavigationLink(destination: Text("Swallow: \(meals.swallow), £\(calculateMeal, specifier: "%.2f")")) {
Text("Create Order")
.font(.system(size: 14))
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(6)
}.padding()
Spacer()
}
}
} //VStack End
} //Section End
} else if menuItems[menuItem] == "Pepper Soups" {
Text("Pepper Soup")
.foregroundColor(.red)
.padding(.horizontal, 25)
Spacer().frame(height:20)
`Text("Pepper soup is normally taken after one has had either Pounded Yam or rice meals. Depending on the audeience, the soup can be lightly spicy to very hot. Pepper soup can be had with either fish or meat")`
.foregroundColor(.blue)
.lineLimit(nil)
.padding(.horizontal, 25)
Spacer().frame(height:60)
//Insert Image
Image("pepperSoupYam")
.resizable()
.frame(width:250, height:250)
.scaledToFit()
.border(Color.black, width: 4)
.padding(.horizontal, 100)
HStack {//Add Stepper Quantity for Pepper Soup
Stepper("Quantity (5 Max)",value: $meals.pepperSoup, in: 0...5)
.padding(.horizontal, 45)
Text("\(meals.pepperSoup): £\(calculateMeal, specifier: "%.2f")")
.padding()
}.padding()
//Inset Order Button
Section {
VStack {
Spacer()
HStack(alignment: .center, spacing: 140) {
Spacer()
Button(action: {}) {
NavigationLink(destination: NewOrders()) {
Text("Create Order")
.font(.system(size: 14))
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(6)
}.padding()
Spacer()
}
}
}
}
}
Spacer()
}.font(.system(size: 14))
.foregroundColor(.purple)
} //Vstack Ending
} //View Ending
}
//This sis going to be the Orders Struct
struct NewOrders: View {
#ObservedObject var orderUpdatedV2 = MealOrders()
#State private var orderUpdate = MenuOption().meals.jollof
var body: some View {
//let mealsU: ContentView
NavigationView{
VStack {
List {
Text("")
}
}
}.navigationBarTitle("Meal Order")
}
}
This line below is incorrect because creates new value, that's why you have nil
#State private var orderUpdate = MenuOption().meals.jollof
instead you need to have (as far as I understood your code)
#Binding var orderUpdate: Int
and pass it in place of creating
NavigationLink(destination: NewOrders(orderUpdate: $meals.jollof)) {
Note: This is the idea, I'm not sure copy/paste will work, because provided your code snapshot is not compilable at my side.

Resources