SwiftUI`@ State`关键字有什么作用? [英] What does the SwiftUI `@State` keyword do?

查看:284
本文介绍了SwiftUI`@ State`关键字有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SwiftUI教程使用@State关键字表示可变用户界面状态:

The SwiftUI tutorial uses the @State keyword to indicate mutable UI state:

@State var showFavoritesOnly = false

它提供了以下摘要:

状态是一个值或一组值,可以随时间变化,并且会影响视图的行为,内容或布局.您可以将属性与@State属性一起使用,以将状态添加到视图中.

State is a value, or a set of values, that can change over time, and that affects a view’s behavior, content, or layout. You use a property with the @State attribute to add state to a view.

  • 关键字的确切含义是什么?
  • 变异@State变量如何导致视图重新计算?
  • body getter中的其他变量如何不可变?
    • What does the keyword mean, exactly?
    • How does mutating a @State variable cause the view to be recomputed?
    • How are other variables immutable within the body getter?
    • 推荐答案

      @State关键字是@propertyWrapper,这是最近在Swift 5.1中引入的功能.如相应提案所述,有点像是值包装器,它避免了样板代码.

      The @State keyword is a @propertyWrapper, a feature just recently introduced in Swift 5.1. As explained in the corresponding proposal, it's sort of a value wrapper avoiding boilerplate code.

      侧面注释:@propertyWrapper以前称为@propertyDelegate,但此后发生了变化.有关更多信息,请参见这篇文章.

      Sidenote: @propertyWrapper has previously been called @propertyDelegate, but that has changed since. See this post for more information.

      官方的@State文档具有以下含义:

      SwiftUI 管理您声明为状态的任何属性的存储. 状态值更改时,视图将使其外观无效,并且 重新计算身体.使用状态作为真​​理的唯一来源 给定视图.

      SwiftUI manages the storage of any property you declare as a state. When the state value changes, the view invalidates its appearance and recomputes the body. Use the state as the single source of truth for a given view.

      状态实例不是值本身;状态实例不是值本身.这是一种 读取并修改值.要访问州的基本价值, 使用其value属性.

      A State instance isn’t the value itself; it’s a means of reading and mutating the value. To access a state’s underlying value, use its value property.

      因此,当初始化标记为@State的属性时,实际上并没有创建自己的变量,而是提示SwiftUI在后台存储存储您所要内容的某物" 从现在开始设置并监视它!您的@State var只是充当访问此包装器的代表.

      So when you initialize a property that's marked @State, you're not actually creating your own variable, but rather prompting SwiftUI to create "something" in the background that stores what you set and monitors it from now on! Your @State var just acts as a delegate to access this wrapper.

      每次写入 变量时,SwiftUI就会知道它正在监视它.它还将知道是否从Viewbody读取了变量.使用此信息,可以在更改此变量后重新计算在其body中引用了@State变量的任何View .

      Every time your @State variable is written, SwiftUI will know as it is monitoring it. It will also know whether the @State variable was read from the View's body. Using this information, it will be able to recompute any View having referenced a @State variable in its body after a change to this variable.

      这篇关于SwiftUI`@ State`关键字有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆