UIViewElement

public protocol UIViewElement : Element

An element type which makes it easier to wrap an existing UIView instance that provides its own sizing via sizeThatFits. An instance of the view is used for sizing and measurement, so that you do not need to re-implement your own measurement.

Note

The sizing and measurement prototype view is kept alive for the lifetime of the containing application. Do not pass anything to the initializer of this type that you expect to be quickly released.

Example

If you were implementing a very basic Switch element, your implementation would look something like this:

struct Switch : UIViewElement
{
    var isOn : Bool

    typealias UIViewType = UISwitch

    func makeUIView() -> UISwitch {
        UISwitch()
    }

    func updateUIView(_ view: UISwitch, with context: UIViewElementContext) {
        view.isOn = self.isOn
    }
}
  • The type of the view associated with the element.

    Declaration

    Swift

    associatedtype UIViewType : UIView
  • Create and return a new instance of the provided view type.

    Note

    Ensure that you do not pass any values to the initializer of your view type that you cannot also update in updateUIView(_:), as view instances are reused for sizing and measurement.

    Declaration

    Swift

    func makeUIView() -> UIViewType
  • Update the view instance with the content from the element. The context provides additional information, such as whether the update is for the measuring instance.

    Example

    If you were to implement a simple UIViewElement which wraps a UISwitch, your update method would look like this:

    func updateUIView(_ view: UISwitch, with context: UIViewElementContext) {
       view.isOn = self.isOn
    }
    

    Declaration

    Swift

    func updateUIView(_ view: UIViewType, with context: UIViewElementContext)
  • size(_:thatFits:) Default implementation

    Returns the sizing measurement for the element for the provided measurement view.

    You usually do not need to implement this method – the default implementation of this method simply calls sizeThatFits(_:) on the provided view.

    The view is fully configured and updated before this method is called – you do not need to update it in any way.

    When To Override

    You may want to override this method if you need to mutate the value returned from sizeThatFits(_:), or if you want to use some other sizing method like systemLayoutSizeFitting(...).

    Default Implementation

    The default implementation simply forwards to sizeThatFits(_:).

    Declaration

    Swift

    func size(_ size: CGSize, thatFits view: UIViewType) -> CGSize

Element