How to put View on top of all other views in SwiftUI - swift

I'm developing SwiftUI test app and I added my custom DropDown menu here.
All works fine except dropdown menu is below other views. So users can't see & click dropdown menu correctly.
Here's my dropdown menu.
import SwiftUI
var dropdownCornerRadius:CGFloat = 3.0
struct DropdownOption: Hashable {
public static func == (lhs: DropdownOption, rhs: DropdownOption) -> Bool {
return lhs.key == rhs.key
}
var key: String
var val: String
}
struct DropdownOptionElement: View {
var dropdownWidth:CGFloat = 150
var val: String
var key: String
#Binding var selectedKey: String
#Binding var shouldShowDropdown: Bool
#Binding var displayText: String
var body: some View {
Button(action: {
self.shouldShowDropdown = false
self.displayText = self.val
self.selectedKey = self.key
}) {
VStack {
Text(self.val)
Divider()
}
}.frame(width: dropdownWidth, height: 30)
.padding(.top, 15).background(Color.gray)
}
}
struct Dropdown: View {
var dropdownWidth:CGFloat = 150
var options: [DropdownOption]
#Binding var selectedKey: String
#Binding var shouldShowDropdown: Bool
#Binding var displayText: String
var body: some View {
VStack(alignment: .leading, spacing: 0) {
ForEach(self.options, id: \.self) { option in
DropdownOptionElement(dropdownWidth: self.dropdownWidth, val: option.val, key: option.key, selectedKey: self.$selectedKey, shouldShowDropdown: self.$shouldShowDropdown, displayText: self.$displayText)
}
}
.background(Color.white)
.cornerRadius(dropdownCornerRadius)
.overlay(
RoundedRectangle(cornerRadius: dropdownCornerRadius)
.stroke(Color.primary, lineWidth: 1)
)
}
}
struct DropdownButton: View {
var dropdownWidth:CGFloat = 300
#State var shouldShowDropdown = false
#State var displayText: String
#Binding var selectedKey: String
var options: [DropdownOption]
let buttonHeight: CGFloat = 30
var body: some View {
Button(action: {
self.shouldShowDropdown.toggle()
}) {
HStack {
Text(displayText)
Spacer()
Image(systemName: self.shouldShowDropdown ? "chevron.up" : "chevron.down")
}
}
.padding(.horizontal)
.cornerRadius(dropdownCornerRadius)
.frame(width: self.dropdownWidth, height: self.buttonHeight)
.overlay(
RoundedRectangle(cornerRadius: dropdownCornerRadius)
.stroke(Color.primary, lineWidth: 1)
)
.overlay(
VStack {
if self.shouldShowDropdown {
Spacer(minLength: buttonHeight)
Dropdown(dropdownWidth: dropdownWidth, options: self.options, selectedKey: self.$selectedKey, shouldShowDropdown: $shouldShowDropdown, displayText: $displayText)
}
}, alignment: .topLeading
)
.background(
RoundedRectangle(cornerRadius: dropdownCornerRadius).fill(Color.white)
)
}
}
struct DropdownButton_Previews: PreviewProvider {
static let options = [
DropdownOption(key: "week", val: "This week"), DropdownOption(key: "month", val: "This month"), DropdownOption(key: "year", val: "This year")
]
static var previews: some View {
Group {
VStack(alignment: .leading) {
DropdownButton(displayText: "This month", selectedKey: .constant("Test"), options: options)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.green)
.foregroundColor(Color.primary)
VStack(alignment: .leading) {
DropdownButton(shouldShowDropdown: true, displayText: "This month", selectedKey: .constant("Test"), options: options)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.green)
.foregroundColor(Color.primary)
}
}
}
Here's how it looks like.
Has anyone faced this issue before? And Could anyone please help me solve this issue?
Thanks.

Try to put everything in ZStack and use zIndex for DropdownButton to put it atop, like
ZStack {
// ... other content here
DropdownButton(displayText: "This month",
selectedKey: .constant("Test"),
options: options).zIndex(10)
// ... other content here

Related

How to append something to a list?

I'm new to Swift at the moment and I'm having trouble appending to a to-do list. I am not receiving an error, so I don't know what's wrong. I hope this isn't too much code to go through, but I don't even know where the problem is.
There is a sheet modal that opens and closes fine. The only issue is that when I press the save button, the information I typed in doesn't add to the list.
I've add the ViewModel, NewTaskView(sheet), TaskView(customizes list), and a bit of code of the DetailView where the list should be.
import Foundation
import SwiftUI
class TaskViewModel : Identifiable , ObservableObject {
#Published var tasks : [Task] = [
Task(taskName: "Lab", taskDate: Date(), taskCompleted: false),
Task(taskName: "Assignment 4.02", taskDate: Date(), taskCompleted: false)
]
#Published var sortType : SortType = .alphabetical
#Published var isPresented = false
#Published var searched = ""
func addTask(task : Task){
tasks.append(task)
}
func removeTask(indexAt : IndexSet){
tasks.remove(atOffsets: indexAt)
}
func sort(){
switch sortType {
case .alphabetical :
tasks.sort(by: { $0.taskName < $1.taskName })
case .date :
tasks.sort(by: { $0.taskDate > $1.taskDate })
}
}
}
struct Task : Identifiable , Equatable {
var id : String = UUID().uuidString
let taskName : String
let taskDate : Date
var taskCompleted: Bool
}
enum SortType : String , Identifiable , CaseIterable {
var id : String { rawValue }
case alphabetical
case date
}
struct NewTaskView: View {
#Environment(\.presentationMode) var presentationMode
#ObservedObject var taskVM : TaskViewModel
#State var taskName = ""
#State var taskCompleted = Bool()
#State var taskDate = Date()
var body: some View {
NavigationView {
VStack(spacing: 14) {
Spacer()
TextField("Assignment Name",text: $taskName)
.padding()
.background(Color("tan"))
.cornerRadius(5)
.font(Font.custom(FontNameManager.Montserrat.semibold, size: 15))
.padding(.bottom, 20)
HStack{
Text("Due Date")
.font(Font.custom(FontNameManager.Montserrat.semibold, size: 15))
Image(systemName: "bell.badge")
.foregroundColor(.gray)
.frame(width: 30, height: 30, alignment: .leading)
VStack{
DatePicker("Select Date", selection: $taskDate, displayedComponents: .date)
.labelsHidden()
}
}
HStack{
Text("Mark as Completed")
.font(Font.custom(FontNameManager.Montserrat.semibold, size: 15))
Button(action : {
taskCompleted.toggle()
}){
if taskCompleted == true {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(Color("orange"))
.font(.title2)
}
else {
Image(systemName: "circle")
.foregroundColor(Color("lightorange"))
.font(.title2)
}
}
}
Spacer()
Button(action:{taskVM.addTask(task: .init(taskName: taskName, taskDate: taskDate, taskCompleted: taskCompleted))
presentationMode.wrappedValue.dismiss()},
label:{
Text("Save")
})
}.padding()
.navigationBarItems(trailing: Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
HStack{
Image(systemName: "xmark")
.foregroundColor(Color("orange"))
}
})
}
}
}
struct NewTaskView_Previews: PreviewProvider {
static var previews: some View {
NewTaskView(taskVM: TaskViewModel())
}
}
struct TaskView: View {
var task : Task
#Environment(\.managedObjectContext) var moc
#State var currentDate: Date = Date()
#State var taskCompleted = false
func getDateFormatString(date:Date) -> String
{
var dateString = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM. dd"
dateString = dateFormatter.string(from: date)
return dateString
}
var body: some View {
HStack {
Button(action : {
self.taskCompleted.toggle()
try? self.moc.save()
}){
if self.taskCompleted {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(Color("orange"))
.font(.title2)
}
else {
Image(systemName: "circle")
.foregroundColor(Color("lightorange"))
.font(.title2)
}
}.padding()
VStack (alignment: .leading, spacing: 2){
Text("\(task.taskName)")
.font(Font.custom(FontNameManager.Montserrat.bold, size: 18))
.foregroundColor(Color("dark"))
.padding([.leading, .trailing], 1)
if self.taskCompleted {
Text("Completed")
.font(Font.custom(FontNameManager.Montserrat.bold, size: 12))
.foregroundColor(Color("burntorange"))
.frame(width: 95, height: 20)
.background(Color("lightorange"))
.cornerRadius(4)
}
else if currentDate > task.taskDate {
Text("Late")
.font(Font.custom(FontNameManager.Montserrat.semibold, size: 12))
.foregroundColor(.white)
.frame(width: 95, height: 18)
.background(Color("lightbrown"))
.cornerRadius(4)
}
else {
let diffs = Calendar.current.dateComponents([.day], from: currentDate, to: task.taskDate )
Text("\(diffs.day!) days left")
.font(Font.custom(FontNameManager.Montserrat.semibold, size: 12))
.foregroundColor(Color("burntorange"))
.frame(width: 95, height: 20)
.background(Color("lightorange"))
.cornerRadius(4)
}
}
Spacer()
Text(getDateFormatString(date: task.taskDate ))
.font(Font.custom(FontNameManager.Montserrat.medium, size: 12))
.padding()
}
.padding(10)
.cornerRadius(10)
.background(
RoundedRectangle(cornerRadius: 10 , style: .continuous)
.foregroundColor(.white))
}
}
struct TaskView_Previews: PreviewProvider {
static var previews: some View {
TaskView(task: Task(id: "", taskName: "Task Name", taskDate: Date(), taskCompleted: false))
}
}
struct DetailsView: View {
#Environment(\.managedObjectContext) var moc
#ObservedObject var developers : Developer
#ObservedObject var taskVM : TaskViewModel
#Environment(\.presentationMode) var presen
#Environment(\.editMode) var editButton
#State var taskCompleted = false
#State var show = false
#State var showSearch = false
#State var txt = ""
#State var currentDate: Date = Date()
#State var image : Data = .init(count: 0)
#State var indices : [Int] = []
func getDateFormatString(date:Date) -> String
{
var dateString = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM. dd"
dateString = dateFormatter.string(from: date)
return dateString
}
var body: some View {
NavigationView {
ZStack {
ZStack{
VStack{
Color("lightorange")
.clipShape(CustomCorners(corners: [.bottomLeft, .bottomRight], size: 70))
.ignoresSafeArea(.all, edges: .top)
.frame(width: 420, height: 175)
Spacer()
}
VStack{
HStack {
if !self.showSearch{
Button(action: {
withAnimation(.spring()){
self.presen.wrappedValue.dismiss()
}
}) {
Image(systemName: "chevron.left")
.font(.title2)
.foregroundColor(Color("dark"))
.padding(10)
}
}
Spacer(minLength: 0)
HStack {
if self.showSearch{
Image(systemName: "magnifyingglass")
.font(.title2)
.foregroundColor(Color("dark"))
.padding(.horizontal, 8)
TextField("Search", text: $taskVM.searched , onEditingChanged: { (isBegin) in
if isBegin {
showSearch = true
} else {
showSearch = false
}
})
Button(action: {
withAnimation{
self.showSearch.toggle()
}
}) {
Image(systemName: "xmark").foregroundColor(.black).padding(.horizontal, 8)
}
}
else {
Button(action: {
withAnimation {
self.showSearch.toggle()
}
}) {
Image(systemName: "magnifyingglass")
.font(.title2)
.foregroundColor(Color("dark"))
.padding(10)
}
}
}.padding(self.showSearch ? 10 : 0)
.background(Color("lightorange"))
.cornerRadius(20)
}
ZStack{
RoundedRectangle(cornerRadius: 25)
.foregroundColor(Color("tan"))
.frame(width: 335, height: 130)
HStack {
VStack (alignment: .leading){
// Image(uiImage: UIImage(data: developers.imageD ?? self.image)!)
// .resizable()
// .frame(width: 70, height: 70)
// .clipShape(RoundedRectangle(cornerRadius: 20))
Text("\(developers.username ?? "")")
.font(Font.custom(FontNameManager.Montserrat.bold, size: 24))
.foregroundColor(Color("dark"))
Text("\(developers.descriptions ?? "")")
.font(Font.custom(FontNameManager.Montserrat.semibold, size: 18))
.foregroundColor(.gray)
}
.padding([.leading, .trailing], 70)
.padding(.bottom, 80)
Spacer()
}
}
HStack{
Text("Assignments")
.font(Font.custom(FontNameManager.Montserrat.bold, size: 20))
Spacer(minLength: 0)
EditButton()
}
.padding([.leading, .trailing], 20)
Spacer()
List {
ForEach (taskVM.tasks.filter {
self.taskVM.searched.isEmpty ? true : $0.taskName.localizedCapitalized.contains(self.taskVM.searched)} ){ task in
TaskView(task: task)
.listRowSeparator(.hidden)
}
.onDelete(perform: {
taskVM.removeTask(indexAt: $0)
})
}
.listStyle(InsetListStyle())
}
}
VStack {
Spacer()
HStack {
Spacer()
ExpandableFAB(taskVM: TaskViewModel(), show: $show)
}
}
}.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}
}
}
struct DetailsView_Previews: PreviewProvider {
static let persistenceController = PersistenceController.shared
static var developers: Developer = {
let context = persistenceController.container.viewContext
let developers = Developer(context: context)
developers.username = "Math"
developers.descriptions = "Calculus"
return developers
}()
static var previews: some View {
DetailsView(developers: developers, taskVM: TaskViewModel()).environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
struct ExpandableFAB: View {
#Environment(\.managedObjectContext) var moc
#ObservedObject var taskVM : TaskViewModel
#Binding var show: Bool
var body: some View{
VStack(spacing: 20){
if self.show{
Button(action: {
taskVM.isPresented.toggle()
}) {
Image(systemName: "list.bullet.rectangle.portrait").resizable().frame(width: 25, height: 25).padding()
}
.foregroundColor(.white)
.background(Color("orange"))
.clipShape(Circle())
Button(action: {
self.show.toggle()
}) {
Image(systemName: "doc.badge.plus").resizable().frame(width: 25, height: 25).padding()
}.foregroundColor(.white)
.background(Color("orange"))
.clipShape(Circle())
}
Button(action: {
self.show.toggle()
}) {
Image(systemName: "plus").resizable().frame(width: 25, height: 25).padding()
}.foregroundColor(.white)
.background(Color("orange"))
.clipShape(RoundedRectangle(cornerRadius: 20))
.padding()
.rotationEffect(.init(degrees: self.show ? 180 : 0))
}.fullScreenCover(isPresented: $taskVM.isPresented, content: {
NewTaskView(taskVM: taskVM)
})
}
}
#burnsi I don't think I have that anywhere. Where should there be one?
Of course you have one and you need one:
ExpandableFAB(taskVM: TaskViewModel(), show: $show)
This line is causing the issue.
You are somehow injecting a TaskViewModel in your DetailsView (You are not showing where), but not using it. Try:
ExpandableFAB(taskVM: taskVM, show: $show)
And the place you create your ViewModel ('TaskViewModel()') should have a #StateObject wrapper.
Explanation:
As you add something to your ViewModel the views depending on the ViewModel get rebuild. So your TaskViewModel ends up beeing recreated and you still have your 2 initial values in your array.

How to conditionally render a SwiftUI Form with animation using the selection from a Segmented Picker?

I'm trying to conditionally render two Forms based on the selection from a segmented picker. It all works fine when there's no animations, but the moment I add them in, the first Form seems to break.
Code for the 1st Form:
struct CalculateView: View {
#Binding var checkAmount: Double
#Binding var numberOfPeople: Int
#Binding var tipPercentage: Int
#Binding var currentMode: DisplayMode
#FocusState var amountIsFocused: Bool
let tipPercentages: [Int]
var currencyType: FloatingPointFormatStyle<Double>.Currency
var grandTotal: Double
var totalPerPerson: Double
var body: some View {
Form{
Section{
TextField("Amount", value: $checkAmount, format:
.currency(code: Locale.current.currencyCode ?? "USD"))
.keyboardType(.decimalPad)
.focused($amountIsFocused)
Picker("Number of people", selection: $numberOfPeople) {
ForEach(1..<100, id: \.self){
Text($0 == 1 ? "\($0) Person" : "\($0) People")
}
}
}
Section{
Picker("Tip Percentage", selection: $tipPercentage){
ForEach(0..<101){
Text($0, format: .percent)
}
}.pickerStyle(.wheel)
} header: {
Text("How much tip do you want to leave ?")
}
Section{
HStack {
Text("Grand Total")
.foregroundColor(.secondary)
.font(.system(size:14, weight: .regular))
.textCase(.uppercase)
Spacer()
Text(grandTotal, format:
currencyType)
.foregroundColor(tipPercentage == 0 ? .red: .blue)
.font(.system(size: 20, weight: .regular))
}.padding(.horizontal, 10)
VStack(alignment: .leading){
Text("Amount per person")
.foregroundColor(.secondary)
.font(.system(size: 15, weight: .semibold))
.padding(EdgeInsets(top: 5, leading: 10, bottom: 0, trailing: 0))
.textCase(.uppercase)
Text(totalPerPerson, format:
.currency(code: Locale.current.currencyCode ?? "USD"))
.frame(maxWidth: .infinity)
.font(.system(size: 55, weight: .thin))
.padding(EdgeInsets(top: 15, leading: 0, bottom: 20, trailing: 0))
.foregroundColor(.green)
}
} header: {
Text("Final Payment")
.foregroundColor(.orange)
}
}
}
}
Code for the 2nd Form:
struct HistoryView: View {
var body: some View {
Form {
Section {
Text("test")
}
}
}
}
Main ContentView code:
enum DisplayMode: String, Equatable, CaseIterable {
case calculate
case history
}
struct ContentView: View {
#State private var checkAmount = 0.0
#State private var numberOfPeople = 2
#State private var tipPercentage = 20
#State private var currentMode: DisplayMode = .calculate
#FocusState private var amountIsFocused: Bool
let tipPercentages = [10, 15, 20, 25, 0]
var currencyType: FloatingPointFormatStyle<Double>.Currency {
return .currency(code: Locale.current.currencyCode ?? "USD")
}
var grandTotal: Double {
let tipValue = checkAmount / 100 * Double(tipPercentage)
let total = checkAmount + tipValue
return total
}
var totalPerPerson: Double {
let peopleCount = Double(numberOfPeople)
let amountPerPerson = grandTotal / peopleCount
return amountPerPerson
}
var navigationTitle: String {
let title = currentMode == .calculate ? "WeSplit" : currentMode.rawValue.capitalized
return title
}
let swapRight: AnyTransition = .asymmetric(
insertion: .move(edge: .trailing),
removal: .move(edge: .leading)
)
let swapLeft: AnyTransition = .asymmetric(
insertion: .move(edge: .leading),
removal: .move(edge: .trailing)
)
var body: some View {
NavigationView{
VStack {
if currentMode == .calculate {
CalculateView(checkAmount: $checkAmount, numberOfPeople: $numberOfPeople, tipPercentage: $tipPercentage, currentMode: $currentMode, amountIsFocused: _amountIsFocused, tipPercentages: tipPercentages, currencyType: currencyType, grandTotal: grandTotal, totalPerPerson: totalPerPerson)
.transition(swapLeft)
} else {
HistoryView()
.transition(swapRight)
}
}
.animation(.easeInOut, value: currentMode)
.navigationTitle(navigationTitle)
.toolbar{
ToolbarItemGroup(placement: .keyboard) {
Button("Done"){
amountIsFocused = false
}
}
ToolbarItemGroup(placement: .principal) {
Picker("Mode", selection: $currentMode) {
ForEach(DisplayMode.allCases, id: \.self){ mode in
Text(mode.rawValue.capitalized)
}
}.pickerStyle(.segmented)
.fixedSize()
}
ToolbarItemGroup(placement: .navigationBarTrailing) {
if currentMode == .calculate {
Button {
print("Save")
} label: {
Text("Save")
}
}
}
}
}
}
}
Here's what it looks like on the simulator:
SwiftUI Form animation glitch
I can reproduce the issue, this seems to be a bug, the console is showing some constraint warnings.
A workaround could be using TabView. A positive side effect is that you won't need custom transitions, they come with it:
NavigationView{
TabView(selection: $currentMode) {
CalculateView(checkAmount: $checkAmount, numberOfPeople: $numberOfPeople, tipPercentage: $tipPercentage, currentMode: $currentMode, amountIsFocused: _amountIsFocused, tipPercentages: tipPercentages, currencyType: currencyType, grandTotal: grandTotal, totalPerPerson: totalPerPerson)
.tag(DisplayMode.calculate)
// .transition(swapLeft)
HistoryView()
.tag(DisplayMode.history)
// .transition(swapRight)
}
.tabViewStyle(.page(indexDisplayMode: .never) )
.animation(.easeInOut, value: currentMode)
// rest of your code as is

How to make an individual button icon change for each ForEach item on SwiftUI?

I am trying to make each individual item button change from a cart icon a different icon when clicked in my ForEach. But when I click on a button every button icon change. How can I fix this?
Thank you so much
#StateObject var vm = ShopViewModel()
#State var isShowing = false
#State var cartItemCount = 0
#State var itemCart = false
var body: some View {
NavigationView {
ScrollView(/*#START_MENU_TOKEN#*/.vertical/*#END_MENU_TOKEN#*/, showsIndicators: false) {
VStack {
ForEach(vm.foods) { food in
HStack {
NavigationLink(
destination: DetailView(foody: food, isCanceled: $isShowing),
label: {
Image(food.imageURL)
.resizable()
.frame(width: /*#START_MENU_TOKEN#*/100/*#END_MENU_TOKEN#*/, height: /*#START_MENU_TOKEN#*/100/*#END_MENU_TOKEN#*/)
Text(food.name)
.bold()
Spacer()
Text("$\(food.price)").padding()
}).foregroundColor(.black)
Spacer()
Button(action: {
cartItemCount += 1
}, label: {
Image(systemName: "cart")
.frame(width: 70, height: 50)
.background(Color("yColor"))
.cornerRadius(30)
}).padding(.trailing, 30)
}.padding(.leading, 20)
}
}.padding(.top, 30)
}
.navigationTitle("Falco Shop")
.navigationBarItems(trailing: CartIcon(cartItemCount: $cartItemCount).padding(.top, 90).padding())
}
}
Here is an example how you can do this:
import SwiftUI
struct ContentView: View {
#StateObject var vm = ShopViewModel()
#State var isShowing = false
#State var cartItemCount = 0
#State var itemCart = false
var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
VStack {
ForEach(vm.foods.indices, id:\.self) { index in
HStack {
Text(vm.foods[index].name)
Spacer()
Button(action: {
cartItemCount += 1
vm.foods[index].selected.toggle()
}, label: {
Image(systemName: vm.foods[index].selected ? "cart.fill" : "cart")
.frame(width: 70, height: 50)
.background(Color("yColor"))
.cornerRadius(30)
}).padding(.trailing, 30)
}.padding(.leading, 20)
}
}.padding(.top, 30)
}
.navigationTitle("Falco Shop")
}
}
}
class ShopViewModel: ObservableObject {
#Published var foods: [Food] = [Food(name: "apple", price: 2.0, selected: false, imageURL: "apple")]
}
struct Food: Identifiable {
let id: UUID = UUID()
var name: String
var price: Double
var selected: Bool
var imageURL: String
}

Why My second view cannot jump back to the root view properly

My App currently has two pages, first page has a circle plus button which could lead us to a second page. Basically, I have a save button which after clicking it, we could get back to the rood page. I followed this link for going back to root view. I tried the most up voted code, his code works perfectly. I reduced his code to two scene (basically the same scenario as mine), which also works perfectly. But then I don't know why my own code, pasted below, doesn't work. Basically my way of handling going back to root view is the same as the one in the link.
//
// ContentView.swift
// refridgerator_app
//
// Created by Mingtao Sun on 12/22/20.
//
import SwiftUI
import UIKit
#if canImport(UIKit)
extension View {
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
#endif
struct ContentView: View {
#EnvironmentObject private var fridge : Fridge
private var dbStartWith=0;
#State var pushed: Bool = false
#State private var selection = 1;
#State private var addFood = false;
var body: some View {
TabView(selection: $selection) {
NavigationView {
List(fridge.container!){
food in NavigationLink(destination: FoodView()) {
Text("HI")
}
}.navigationBarTitle(Text("Fridge Items"), displayMode: .inline)
.navigationBarItems(trailing:
NavigationLink(destination: AddFoodView(pushed: self.$pushed),isActive: self.$pushed) {
Image(systemName: "plus.circle").resizable().frame(width: 22, height: 22)
}.isDetailLink(false) )
}
.tabItem {
Image(systemName: "house.fill")
Text("Home")
}
.tag(1)
Text("random tab")
.font(.system(size: 30, weight: .bold, design: .rounded))
.tabItem {
Image(systemName: "bookmark.circle.fill")
Text("profile")
}
.tag(0)
}.environmentObject(fridge)
}
}
struct FoodView: View{
var body: some View{
NavigationView{
Text("food destination view ");
}
}
}
struct AddFoodView: View{
#Binding var pushed : Bool
#EnvironmentObject private var fridgeView : Fridge
#State private var name = ""
#State private var count : Int = 1
#State private var category : String = "肉类";
#State var showCategory = false
#State var showCount = false
var someNumberProxy: Binding<String> {
Binding<String>(
get: { String(format: "%d", Int(self.count)) },
set: {
if let value = NumberFormatter().number(from: $0) {
self.count = value.intValue;
}
}
)
}
var body: some View{
ZStack{
NavigationView{
VStack{
Button (action: {
self.pushed = false ;
//let tempFood=Food(id: fridgeView.index!,name: name, count: count, category: category);
//fridgeView.addFood(food: tempFood);
} ){
Text("save").foregroundColor(Color.blue).font(.system(size: 18,design: .default)) }
}.navigationBarTitle("Three")
}
ZStack{
if self.showCount{
Rectangle().fill(Color.gray)
.opacity(0.5)
VStack(){
Spacer(minLength: 0);
HStack{
Spacer()
Button(action: {
self.showCount=false;
}, label: {
Text("Done")
}).frame(alignment: .trailing).offset(x:-15,y:15)
}
Picker(selection: $count,label: EmptyView()) {
ForEach(1..<100){ number in
Text("\(number)").tag("\(number)")
}
}.labelsHidden()
} .frame(minWidth: 300, idealWidth: 300, maxWidth: 300, minHeight: 250, idealHeight: 100, maxHeight: 250, alignment: .top).fixedSize(horizontal: true, vertical: true)
.background(RoundedRectangle(cornerRadius: 27).fill(Color.white.opacity(1)))
.overlay(RoundedRectangle(cornerRadius: 27).stroke(Color.black, lineWidth: 1))
.offset(x:10,y:-10)
Spacer()
}
if self.showCategory{
let categoryArr = ["肉类","蔬菜类","饮料类","调味品类"]
ZStack{
Rectangle().fill(Color.gray)
.opacity(0.5)
VStack(){
Spacer(minLength: 0);
HStack{
Spacer()
Button(action: {
self.showCategory=false;
}, label: {
Text("Done")
}).frame(alignment: .trailing).offset(x:-15,y:15)
}
Picker(selection: $category,label: EmptyView()) {
ForEach(0..<categoryArr.count){ number in
Text(categoryArr[number]).tag(categoryArr[number])
}
}.labelsHidden()
} .frame(minWidth: 300, idealWidth: 300, maxWidth: 300, minHeight: 250, idealHeight: 100, maxHeight: 250, alignment: .top).fixedSize(horizontal: true, vertical: true)
.background(RoundedRectangle(cornerRadius: 27).fill(Color.white.opacity(1)))
.overlay(RoundedRectangle(cornerRadius: 27).stroke(Color.black, lineWidth: 1))
Spacer()
}.offset(x:10,y:20)
}
}
}.animation(.easeInOut)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
If you read my code carefully, there are some variables are missing referencing. That's because I pasted part of the code that relates to my issue.
Food Class
//
// Food.swift
// refridgerator_app
//
// Created by Mingtao Sun on 12/23/20.
//
import Foundation
class Food: Identifiable {
init(id:Int, name: String, count: Int, category: String){
self.id=id;
self.name=name;
self.count=count;
self.category=category;
}
var id: Int
var name: String
var count: Int
var category: String
}
Fridge class
//
// Fridge.swift
// refridgerator_app
//
// Created by Mingtao Sun on 12/27/20.
//
import Foundation
class Fridge: ObservableObject{
init(){
db=DBhelper();
let result = setIndex(database: db!);
self.index = result.1;
self.container=result.0;
}
var db:DBhelper?
var index : Int?
#Published var container : [Food]?;
func setIndex(database: DBhelper) -> ([Food],Int){
let foodList : [Food] = database.read();
var index=0;
for food in foodList{
index = max(food.id,index);
}
return (foodList,(index+1));
}
func updateindex(index: inout Int){
index=index+1;
}
func testExist(){
if let data = db {
print("hi")
}
else{
print("doesnt exist")
}
}
func addFood(food:Food){
self.db!.insert(id: self.index!, name: food.name, count:food.count, category: food.category);
self.container!.append(food);
}
}
Because you implemented a new NaviagtionView in AddFoodView. Simply remove this and it should work. Look at the link you provided. There is no NavigationView in the child.
Correct me if Im wrong but the core code parts here that produce this issue are as follows:
Here you start:
struct ContentView: View {
#State var pushed: Bool = false
// Deleted other vars
var body: some View {
TabView(selection: $selection) {
NavigationView {
List(fridge.container!){
food in NavigationLink(destination: FoodView()) {
Text("HI")
}
}.navigationBarTitle(Text("Fridge Items"), displayMode: .inline)
.navigationBarItems(trailing:
// Here you navigate to the child view
NavigationLink(destination: AddFoodView(pushed: self.$pushed),isActive: self.$pushed) {
Image(systemName: "plus.circle").resizable().frame(width: 22, height: 22)
}.isDetailLink(false) )
}
Here you land and want to go back to root:
struct AddFoodView: View{
#Binding var pushed : Bool
// Deleted the other vars for better view
var body: some View{
ZStack{
NavigationView{ // <-- remove this
VStack{
Button (action: {
// here you'd like to go back
self.pushed = false;
} ){
Text("save").foregroundColor(Color.blue).font(.system(size: 18,design: .default)) }
}.navigationBarTitle("Three")
}
For the future:
I have the feeling you might have troubles with the navigation in general.
Actually it is really simple:
You implement one NavigationView at the "root" / start of your navigation.
From there on you only use NavigationLinks to go further down to child pages. No NavigationView needed anymore.

How to add click event to whole view in SwiftUI

I'm developing SwiftUI test app and I added my custom DropDown menu here.
Dropdown works fine but I want to dismiss dropdown menu when user click dropdown menu outside area.
Here's my dropdown menu.
import SwiftUI
var dropdownCornerRadius:CGFloat = 3.0
struct DropdownOption: Hashable {
public static func == (lhs: DropdownOption, rhs: DropdownOption) -> Bool {
return lhs.key == rhs.key
}
var key: String
var val: String
}
struct DropdownOptionElement: View {
var dropdownWidth:CGFloat = 150
var val: String
var key: String
#Binding var selectedKey: String
#Binding var shouldShowDropdown: Bool
#Binding var displayText: String
var body: some View {
Button(action: {
self.shouldShowDropdown = false
self.displayText = self.val
self.selectedKey = self.key
}) {
VStack {
Text(self.val)
Divider()
}
}.frame(width: dropdownWidth, height: 30)
.padding(.top, 15).background(Color.gray)
}
}
struct Dropdown: View {
var dropdownWidth:CGFloat = 150
var options: [DropdownOption]
#Binding var selectedKey: String
#Binding var shouldShowDropdown: Bool
#Binding var displayText: String
var body: some View {
VStack(alignment: .leading, spacing: 0) {
ForEach(self.options, id: \.self) { option in
DropdownOptionElement(dropdownWidth: self.dropdownWidth, val: option.val, key: option.key, selectedKey: self.$selectedKey, shouldShowDropdown: self.$shouldShowDropdown, displayText: self.$displayText)
}
}
.background(Color.white)
.cornerRadius(dropdownCornerRadius)
.overlay(
RoundedRectangle(cornerRadius: dropdownCornerRadius)
.stroke(Color.primary, lineWidth: 1)
)
}
}
struct DropdownButton: View {
var dropdownWidth:CGFloat = 300
#State var shouldShowDropdown = false
#State var displayText: String
#Binding var selectedKey: String
var options: [DropdownOption]
let buttonHeight: CGFloat = 30
var body: some View {
Button(action: {
self.shouldShowDropdown.toggle()
}) {
HStack {
Text(displayText)
Spacer()
Image(systemName: self.shouldShowDropdown ? "chevron.up" : "chevron.down")
}
}
.padding(.horizontal)
.cornerRadius(dropdownCornerRadius)
.frame(width: self.dropdownWidth, height: self.buttonHeight)
.overlay(
RoundedRectangle(cornerRadius: dropdownCornerRadius)
.stroke(Color.primary, lineWidth: 1)
)
.overlay(
VStack {
if self.shouldShowDropdown {
Spacer(minLength: buttonHeight)
Dropdown(dropdownWidth: dropdownWidth, options: self.options, selectedKey: self.$selectedKey, shouldShowDropdown: $shouldShowDropdown, displayText: $displayText)
}
}, alignment: .topLeading
)
.background(
RoundedRectangle(cornerRadius: dropdownCornerRadius).fill(Color.white)
)
}
}
struct DropdownButton_Previews: PreviewProvider {
static let options = [
DropdownOption(key: "week", val: "This week"), DropdownOption(key: "month", val: "This month"), DropdownOption(key: "year", val: "This year")
]
static var previews: some View {
Group {
VStack(alignment: .leading) {
DropdownButton(displayText: "This month", selectedKey: .constant("Test"), options: options)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.green)
.foregroundColor(Color.primary)
VStack(alignment: .leading) {
DropdownButton(shouldShowDropdown: true, displayText: "This month", selectedKey: .constant("Test"), options: options)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.green)
.foregroundColor(Color.primary)
}
}
}
I think I can achieve this by adding click event to whole body view and set dropdown show State flag variable to false.
But I'm not sure how to add click event to whole view.
Can anyone please help me about this issue?
Thanks.
You can try like the following in your window ContentView
struct ContentView: View {
var body: some View {
GeometryReader { gp in // << consumes all safe space
// all content here
}
.onTapGesture {
// change state closing any dropdown here
}
}
// .edgesIgnoringSafeArea(.all) // uncomment if needed entire screen
}
can be done adding .contentShape(Rectangle()) to HStack/VStack before .onTapGesture
for example
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
VStack(alignment:.leading, spacing: 8) {
CustomText(text: model?.id ?? "Today", fontSize: 12, fontColor: Color("Black50"))
CustomText(text: model?.title ?? "This Day..", fontSize: 14)
.lineLimit(2)
.padding(.trailing, 8)
}
Spacer()
Image("user_dummy")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 60)
.cornerRadius(8)
}
CustomText(text: model?.document ?? "", fontSize: 12, fontColor: Color("Black50"))
.lineLimit(4)
}
.contentShape(Rectangle())
.onTapGesture {
debugPrint("Whole view as touch")
}
}