How do view types like Text or Image conform to the View protocol in SwiftUI?

前端 未结 4 1165
后悔当初
后悔当初 2021-02-20 08:39

There is one big thing that confuses me about view types in SwiftUI:

They don\'t seem to conform to the View protocol, but somehow, they mysterious

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 08:57

    As you know there are 2 types are Views..

    1. Primitive view: Text, Image, Circle etc
    2. Container view: List, HStack, VStack etc

    That said, below is an extension for Text, Body is set to Never which means its not allowed to have a body because it is a primitive view that is meant for ending body cycle.

    So,(per my understanding) at runtime SwiftUI wraps Text inside a container view when it finds a primitive view not being inside a container view.

    @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
    extension Text {
    
        /// 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.
        public typealias Body = Never
    }
    

提交回复
热议问题