V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
find456789
V2EX  ›  问与答

swiftui 里 VIew 中声明的属性会变成参数?那为什么 body 没有变成参数?

  •  
  •   find456789 · 2021-08-07 14:43:04 +08:00 · 619 次点击
    这是一个创建于 994 天前的主题,其中的信息可能已经有所发展或是发生改变。
    struct DemoView: View {
        var a = 1
        let b = 2
        var body: some View {
            Image("avatar")
        }
    }
    

    比如上面这一段代码,如果在别处引用了 这个 DemoView, 就可以传入参数 a, 但是却不用传入 body,

    但是 body 也 是 DemoVIew 内部的 var 呀

    有朋友知道为什么吗? 有这方面专门讲解的资料吗(讲解 View 内部的 var 、let 的资料),

    我发现很多入门资料都没有针对这个问题讲解(应该是我没有找到讲解这方面的资料)

    补充:我有 react 基础

    谢谢

    4 条回复    2021-08-07 18:30:28 +08:00
    ryh
        1
    ryh  
       2021-08-07 15:19:34 +08:00
    body 不是计算后( computed )的参数吗,a/b 有默认值的也不用传参数啊

    @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
    public protocol View {

    /// The type of view representing the body of this view.
    ///
    /// When you create a custom view, Swift infers this type from your
    /// implementation of the required ``View/body-swift.property`` property.
    associatedtype Body : View

    /// The content and behavior of the view.
    ///
    /// When you implement a custom view, you must implement a computed
    /// `body` property to provide the content for your view. Return a view
    /// that's composed of primitive views that SwiftUI provides, plus other
    /// composite views that you've already defined:
    ///
    /// struct MyView: View {
    /// var body: some View {
    /// Text("Hello, World!")
    /// }
    /// }
    ryh
        2
    ryh  
       2021-08-07 15:24:57 +08:00   ❤️ 1
    m1ng
        3
    m1ng  
       2021-08-07 15:58:09 +08:00   ❤️ 1
    这不是 swiftUI 的问题,是 swift 语言的问题。a 和 b 是存储属性,需要占用 struct 存储空间; body 是计算属性,不占用存储空间,值是通过后面的函数计算出来的。
    find456789
        4
    find456789  
    OP
       2021-08-07 18:30:28 +08:00
    @ryh @m1ng
    谢谢,是我 swift 基础不扎实, 重新补充了下 struct 的知识,我就明白了, 感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2631 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:29 · PVG 08:29 · LAX 17:29 · JFK 20:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.