【问题标题】:How to move to another View by button using a SwiftUI - swift 5.5如何使用 SwiftUI 按按钮移动到另一个视图 - swift 5.5
【发布时间】:2022-01-20 13:35:27
【问题描述】:

例如,这是一个视图:

struct ContentA: View {
var body: some View {
   Text(“Hello”)
    }
}

struct ContentB: View {
var body: some View {

Button("Lets Go!") {
         // Here i wanna to move to ContentA view   
        }
    }
}

我想要一种通过按钮到达 ContentA 视图的方法。

喜欢这张照片:Here

【问题讨论】:

标签: ios swift swiftui


【解决方案1】:

使用 SwiftUI 最简单的方法是 NavigationLink。我已经测试了这个解决方案的工作。您还可以将视图显示为工作表。我会在这里寻找那个解决方案。 https://www.hackingwithswift.com/quick-start/swiftui/how-to-present-a-new-view-using-sheets

我相信NavigationLink 解决方案也要求您拥有NavigationView

import SwiftUI

struct ContentA: View {
var body: some View {
    Text("Hello")
    }
}

struct ContentB: View {
var body: some View {
    NavigationView {
        NavigationLink("Link to A", destination: ContentA())
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentB()
    }
}

【讨论】:

【解决方案2】:

您可以通过对您想要访问的特定视图的这个简单调用来做到这一点。如果您想访问 contentAView,那么只需像这样在按钮操作空间中调用它

struct ContentA: View {
    var body: some View {
       Text("Hello")
        }
    }
    
struct ContentB: View {
    @State var showContentA = false
    var body: some View {
        
        NavigationView{
            Button("Lets Go!") {
                showContentA = true
                
            }
        }
        .sheet(isPresented: $showContentA) {
            ContentA()
        }
    }
}

【讨论】:

  • 这段代码会给你一个“'ContentA'初始值设定项的结果未使用”错误。
  • 是的,我现在可以看到,答案应该是固定的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多