更改 swiftui 视图内的布尔值
我有布尔变量(isTapped),应用程序启动后,我给它一个真实值,一旦它移动到(signupView),应用程序应该测试 if 语句内的值以显示一些文本,之后应用程序应该更改(isTapped) 的值为 false!
但它不起作用! as Type()无法确认查看。 我尝试创建一个函数并在视图中调用它,但它也不起作用! 这是我的代码:
import SwiftUI
struct SignupView: View {
@AppStorage("isTapped") var isTapped : Bool?
var body: some View {
if (isTapped == true){
Text ("signup")
isTapped = false
}
else {
Text ("Splash")
}
}
}
I have boolean variable (isTapped), once the app is launched, I'am giving it a true value, once it moves to (signupView) the app should test the value inside if statement to show some text and after that the app should change the value of (isTapped) to false!!
But it is not working!! as Type () cannot confirm to view.
I tried to create a function and call it inside a view but it is not working either!
Here is my code:
import SwiftUI
struct SignupView: View {
@AppStorage("isTapped") var isTapped : Bool?
var body: some View {
if (isTapped == true){
Text ("signup")
isTapped = false
}
else {
Text ("Splash")
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望在
isTapped
为 True 时显示Text("signup")
,则需要额外的变量来保留原始值您需要设置
isTapped = true
某处可以看到这样的Text("signup")
如果您只想在启动应用程序时显示
signup
一次,则应该像这样If you want
Text("signup")
should be shown whenisTapped
is True, you need additional variable to keep the origin valueYou need to set
isTapped = true
somewhere to seeText("signup")
like thisIf you want to show
signup
only once when launch app it should be like this您无法对视图层次结构内的变量设置任何内容。
因此,为了实现您想要做的事情,也许您可以尝试以下操作:
onAppear
闭包在视图层次结构之外运行,因此您可以将值设置为变量。**更新:回复:您的评论,这就是 SwiftUI 的工作原理。当在
onAppear
中设置isTapped = false
时,SwiftUI 会立即重新加载正文并显示启动画面。我认为要实现您所需要的,您不应该使用@AppStorage
。更新的时候会引起body的更新。为什么不直接使用UserDefaults
这样呢?:...
You can't set anything to a variable inside the view hierarchy.
So to achieve what you want to do, maybe you could try this:
onAppear
closure is run outside the view hierarchy, so you can set values to a variable.**Update: Re: your comment, that's how SwiftUI works. When
isTapped = false
is set inonAppear
, SwiftUI immediately reloads the body and the splash will be shown. I think to achieve what you need, you shouldn't use@AppStorage
. It will cause an update of the body when it's updated. Why don't you just useUserDefaults
like this?:...