为什么我的第二个视图无法正确跳回到根视图

  • 本文关键字:视图 第二个 swift swiftui
  • 更新时间 :
  • 英文 :


我的应用程序目前有两个页面,第一页有一个圆圈加号按钮,可以将我们带到第二页。基本上,我有一个保存按钮,单击它后,我们可以返回 rood 页面。我点击了此链接返回根视图。我尝试了投票最多的代码,他的代码运行良好。我将他的代码简化为两个场景(与我的场景基本相同),这也非常有效。但是我不知道为什么我自己的代码,粘贴在下面,不起作用。基本上,我处理返回根视图的方式与链接中的相同。

//
//  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()
}
}

如果您仔细阅读我的代码,就会发现缺少一些变量引用。那是因为我粘贴了与我的问题相关的部分代码。

食品类

//
//  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.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);
}


}

因为您在AddFoodView中实现了一个新的NaviagtionView。只需删除它,它应该可以工作。查看您提供的链接。孩子没有NavigationView

如果我错了,请纠正我,但这里产生此问题的核心代码部分如下:

从这里开始:

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) )
}

在这里你着陆并想回到根:

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")
}

对于未来:

我感觉您可能会在导航方面遇到麻烦。

其实很简单:

您可以在导航的"根"/开头实现一个NavigationView。 从那里开始,您只能使用NavigationLinks进一步向下访问子页面。不再需要NavigationView了。

相关内容

最新更新