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
等。