在swiftui中单击按钮后如何根据条件显示不同的警报 [英] how to show different alerts based on a condition after clicking a button in swiftui
问题描述
在将其发布到这里之前,我做了一些研究,但是我无法修复它.
I did some research before posting it here but I was not able to fix it.
在注册视图中,我希望用户注册.
In the register View I want the user to register.
我创建了一个链表,并在用户注册用户名时,我的程序检查用户名是否已被使用.
I created a linked list and as user registers a username my program checks whether or not the username is already taken.
如果采取了该措施,则应发出警报,提示用户单击注册按钮时该用户名已采取.
if it is taken it should give an alert saying that the username is already taken as the user clicks the register button.
如果未使用用户名,则应显示一条警告,提示注册成功
if the username is not taken then it should show an alert saying the registration is successful
import SwiftUI
struct registerScreen: View {
@State var username: String = ""
@State var password: String = ""
@State private var sucessfulRegister = false
@State private var failedRegister = false
var body: some View {
VStack {
TextField()
SecureField()
Button(action: {
let userinfo = linkedList()
if (userinfo.contains(value: self.username)){
// self.failedRegister = true
self.failedRegister.toggle()
// show alert that it failed
} else {
userinfo.insert(value: user(username: self.username, password: self.password))
// show alert that it is successfull
self.sucessfulRegister.toggle()
}
})
{
Text("Register")
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(width: 220, height: 60)
.background(Color.green)
.cornerRadius(15.0)
}
}
}
}
推荐答案
可以做到.尽管您不需要跟踪尽可能多的状态.
It is possible to do. Though you don't need to track as many states as you are.
首先,您只需要跟踪它们是否失败.因此,您的failedRegister
将跟踪用户是否已成功注册.这意味着我们可以删除successfulRegister
.
Firstly, you only need to track if they have failed or not. So your failedRegister
will track if the user has successfully registered or not. That means we can get remove the successfulRegister
.
我们需要一个变量来跟踪是否显示警报,为此,我们将使用变量showAlert
We need a variable to track whether an alert is showing or not, for this we will use the variable showAlert
当您有一个提供用户信息的链接列表时,我们将仅使用包含几个用户名的数组来对此进行模拟.
As you have a linked list that provides the userinfo, we will mock that with just an array containing a couple of usernames.
这是应该工作的简化代码.
So here is a simplified version of your code that should work.
struct ContentView: View {
var names: [String] = ["John", "Mike"]
@State var username: String = ""
@State var password : String = ""
@State private var failedRegister = false
// this value is used for tracking whether the alert should be shown
@State private var showAlert = false
var body: some View {
VStack {
TextField("Enter username", text: $username)
Button(action: {
// reset to false as this is the initial state
self.failedRegister = false
if (self.names.contains(self.username)){
self.failedRegister.toggle()
} else {
// insert the value into the user info
}
self.showAlert.toggle()
}) {
Text("Register")
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(width: 220, height: 60)
.background(Color.green)
.cornerRadius(15.0)
}
}.alert(isPresented: $showAlert) {
// it would be nice to set failedRegister back to false in this function but you cannot modify state here.
if self.failedRegister {
return Alert(title: Text("Failed to register"), message: Text("Unfortunately that username is taken"), dismissButton: .default(Text("OK")))
} else {
return Alert(title: Text("Welcome"), message: Text("You have registered"), dismissButton: .default(Text("OK")))
}
}
}
}
使用可识别的更新
有另一种方法可以在同一View
上显示不同的Alerts
.这是要使用对Identifiable
对象的绑定.
Update using Identifiable
There is an alternative way to show different Alerts
on the same View
. This is to use a binding to an object that is Identifiable
.
如果我们看一下在View
上初始化Alert
的方式,我们看到有两种方式.第一个具有以下签名:
If we look at the ways we can initialise an Alert
on a View
we see there are two ways. The first has the following signature:
.alert(isPresented: Binding<Bool>, content: () -> Alert)
上面的示例中使用的是
但是,第二种方法具有以下签名:
However there is a second way which has the following signature:
.alert(item: Binding<Identifiable?>, content: (Identifiable) -> Alert)
第二种方法可以管理更复杂的警报.为了利用这一点,我们需要一些跟踪警报状态的东西.我们可以创建一个符合Identifiable
的简单结构,并包含一个警报的不同选择的枚举.
This second way can allow for more complex alerts to be managed. To utilise this we need something to track the state of the alerts. We can create a simple struct that conforms to Identifiable
and contains an enum of the different choices that we have for an alert.
然后我们创建一个@State
变量以跟踪AlertIdentifier
并将其初始化为nil
,以便其状态为空,并且在更改之前不会显示任何警报.
We then create an @State
variable to track the AlertIdentifier
and initialise to nil
so that its state is empty and will not show any alerts until it is changed.
然后我们可以将.alert(item:content:)
添加到View
.
We can then add our .alert(item:content:)
to our View
.
这是一个简单的示例,展示了它的实际作用.
Here is a simple example showing it in action.
struct ContentView:View {
private struct AlertIdentifier: Identifiable {
var id: Choice
enum Choice {
case success
case failure
}
}
@State private var showAlert: AlertIdentifier? // init this as nil
var body: some View {
VStack(spacing: 20) {
Button(action: {
self.showAlert = AlertIdentifier(id: .success)
}, label: {
Text("Show success alert")
})
Button(action: {
self.showAlert = AlertIdentifier(id: .failure)
}, label: {
Text("Show failure alert")
})
}
.alert(item: $showAlert) { alert -> Alert in
switch alert.id {
case .success:
return Alert(title: Text("Success"), message: Text("You have successfully registered"), dismissButton: .default(Text("OK")))
case .failure:
return Alert(title: Text("Failure"), message: Text("You have failed to register"), dismissButton: .default(Text("OK")))
}
}
}
}
请注意,在按钮中,我们将showAlert
设置为具有要显示的警报类型的结构AlertIdentifier
的实例.在这种情况下,我们有两种类型:成功和失败(但我们可以根据需要选择任意数量的类型,并且我们不需要使用名称 success 和 failure ).设置好之后,它将显示相应的警报.
Notice that in the buttons we set the showAlert
to be an instance of the struct AlertIdentifier
with the type of alert we want to show. In this case we have two types: success and failure (but we could have as many types as we want, and we don't need to use the names success and failure). When that is set, it will show the appropriate alert.
在我们的.alert(item:content:)
中,我们切换了不同的id
,以便我们确保为正确的选择显示正确的警报.
In our .alert(item:content:)
we switch over the different id
s so that we can make sure that the correct alert is shown for the correct choice.
此方法比具有多个布尔值容易得多,并且扩展起来也更容易.
This method is much easier than having multiple booleans, and it is easier to extend.
Sheets
和ActionSheets
的显示方式与Alerts
非常相似.呈现Sheets
的方法有四种.
Sheets
and ActionSheets
are very similar to Alerts
in how they are presented. There are four ways to present Sheets
.
这两个需要Bool
绑定:
.sheet(isPresented: Binding<Bool>, content: () -> View)
.sheet(isPresented: Binding<Bool>, onDismiss: (() -> Void)?, content: () -> Void)
这两个需要Identifiable
绑定:
.sheet(item: Binding<Identifiable?>, content: (Identifiable) -> View)
.sheet(item: Binding<Identifiable?>, onDismiss: (() -> Void)?, content: (Identifiable) -> View)
对于ActionSheets
,有两种方法,例如Alerts
.
For ActionSheets
there are two ways, like Alerts
.
具有Bool
绑定:
.actionSheet(isPresented: Binding<Bool>, content: () -> ActionSheet)
具有Identifiable
绑定:
.actionSheet(item: Binding<Identifiable?>, content: (Identifiable) -> ActionSheet)
我应该使用哪个绑定?
Binding< Bool>
如果只需要显示一种Alert
,Sheet
或ActionSheet
类型,然后使用Bool
绑定,则可以省去编写一些额外的代码行的时间.
Which binding should I use?
Binding<Bool>
If you only need to show one type of Alert
, Sheet
or ActionSheet
then use the Bool
binding, it saves you having to write some extra lines of code.
如果要显示许多不同类型的Alert
,Sheet
或ActionSheet
,请选择Identifiable
绑定,因为它使管理变得更加容易.
If you many different types of Alert
s, Sheet
s or ActionSheet
s to show then choose the Identifiable
binding as it makes it much easier to manage.
可识别对象的更简单版本是使用枚举而不将其包装在结构中.在这种情况下,我们需要符合Identifiable,因此我们需要一个计算所得的属性来存储id值.我们还需要确保枚举使用RawRepresentable,以便我们可以获取唯一ID的值.我建议使用Int或String.在下面的示例中,我使用的是Int.
A simpler version of the identifiable object would be to use an enum without wrapping it in a struct. In this case we need to conform to Identifiable so we need a computed property to store the id value. We also need to make sure that the enum uses a RawRepresentable so that we can get a value for the id that is unique. I would suggest using an Int or a String. In the example below I am using an Int.
enum Choice: Int, Identifiable {
var id: Int {
rawValue
}
case success, failure
}
然后在视图中我们可以执行以下操作:
Then in the view we could do the following:
struct ContentView:View {
enum Choice: Int, Identifiable {
var id: Int {
rawValue
}
case success, failure
}
@State private var showAlert: Choice? // init this as nil
var body: some View {
VStack(spacing: 20) {
Button(action: {
self.showAlert = .success
}, label: {
Text("Show success alert")
})
Button(action: {
self.showAlert = .failure
}, label: {
Text("Show failure alert")
})
}
.alert(item: $showAlert) { alert -> Alert in
switch alert {
case .success:
return Alert(title: Text("Success"), message: Text("You have successfully registered"), dismissButton: .default(Text("OK")))
case .failure:
return Alert(title: Text("Failure"), message: Text("You have failed to register"), dismissButton: .default(Text("OK")))
}
}
}
}
这篇关于在swiftui中单击按钮后如何根据条件显示不同的警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!