与UIKit中的UIView不同的是,在SwiftUI中View不再是一个类而是一个协议

发布时间:2022-11-30浏览次数:0

支持注册ChatGPT Plus的OneKey虚拟卡
绑定Apple Pay、Google Pay、支付宝和微信支付进行日常消费

注册和了解更多 ->

silver

SwiftUI中一切皆View,不论是我们熟悉的Button还是backgroundColor,甚至Color.red,它们都是View

与UIKit中的UIView不同的是,在SwiftUI中View不再是一个类而是一个协议。

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 `body` property.
    associatedtype Body : View

    /// The content and behavior of the view.
    @ViewBuilder var body: Self.Body { get }
}

SwiftUI中的View是不能直接使用的,否则会报错 {% label danger@'View' cannot be constructed because it has no accessible initializers %},当你遇到这个问题的时候请仔细思考一下你是不是真的要这么用,或许可以用一个其他的代替。

常用到的View有:Text/Button/Toggle/Picker/V(Z)(H)Stack/Color/Spacer/Image/Shape/Divider以及它们的modifier等。

字节笔记本扫描二维码查看更多内容