我正在使用 SwiftUI 开发一个简单的 iOS 应用程序,其中包含两个视图:aLogInView()和HomeView().
我想要的非常简单:当用户单击登录按钮时,LogInView()我希望应用程序隐藏LogInView()并显示HomeView()全屏,而不是像模态那样并且不允许用户返回。
这可以通过 Swift 和 UIKit 中的 Storyboards 轻松完成,有没有办法用 SwiftUI 做到这一点?
任何帮助表示赞赏。提前致谢。
我的代码:
登录查看:
struct LogInView: View {
var body: some View {
VStack {
Text("Welcome to Mamoot!")
.font(.largeTitle)
.fontWeight(.heavy)
Text("We are glad to have you here.")
Text("Please log in with your Mastodon or Twitter account to continue.")
.multilineTextAlignment(.center)
.lineLimit(4)
.padding()
Spacer()
FloatingTextField(title: "Username", placeholder: "Username", width: 300, type: "Username")
FloatingTextField(title: "Password", placeholder: "Password", width: 300, type: "password")
.padding(.top, -50)
Spacer()
ZStack {
Button(action: { /* go to HomeView() */ }) {
Text("Log in")
.foregroundColor(Color.white)
.bold()
.shadow(color: .red, radius: 10)
}
.padding(.leading, 140)
.padding(.trailing, 140)
.padding(.top, 15)
.padding(.bottom, 15)
.background(Color.red)
.cornerRadius(10)
}
.padding(.bottom)
}
}
}
Run Code Online (Sandbox Code Playgroud)
主页视图:
struct HomeView: View {
var body: some View {
Text("Home Page")
}
}
Run Code Online (Sandbox Code Playgroud)
更新:我有时间更新答案,并添加过渡。请注意,我更改了 Group by VStack,否则转换不起作用。
您可以更改withAnimation通话的持续时间(按钮关闭)。
我还在你的按钮中移动了一些修饰符,所以整个事情都是“可点击的”。否则,只有点击按钮的文本才会触发操作。
您可以使用ObservedObject、EnvironmentObject或Binding。这是一个示例ObservedObject:
import SwiftUI
class Model: ObservableObject {
@Published var loggedIn = false
}
struct ContentView: View {
@ObservedObject var model = Model()
var body: some View {
VStack {
if model.loggedIn {
HomeView().transition(.opacity)
} else {
LogInView(model: model).transition(.opacity)
}
}
}
}
struct HomeView: View {
var body: some View {
Text("Home Page")
}
}
struct LogInView: View {
@ObservedObject var model: Model
var body: some View {
VStack {
Text("Welcome to Mamoot!")
.font(.largeTitle)
.fontWeight(.heavy)
Text("We are glad to have you here.")
Text("Please log in with your Mastodon or Twitter account to continue.")
.multilineTextAlignment(.center)
.lineLimit(4)
.padding()
Spacer()
// FloatingTextField(title: "Username", placeholder: "Username", width: 300, type: "Username")
// FloatingTextField(title: "Password", placeholder: "Password", width: 300, type: "password")
// .padding(.top, -50)
Spacer()
ZStack {
Button(action: {
withAnimation(.easeInOut(duration: 1.0)) {
self.model.loggedIn = true
}
}) {
Text("Log in")
.foregroundColor(Color.white)
.bold()
.shadow(color: .red, radius: 10)
// moved modifiers here, so the whole button is tappable
.padding(.leading, 140)
.padding(.trailing, 140)
.padding(.top, 15)
.padding(.bottom, 15)
.background(Color.red)
.cornerRadius(10)
}
}
.padding(.bottom)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2236 次 |
| 最近记录: |