Skip to main content

LayoutAlgorithm

Trait LayoutAlgorithm 

Source
pub trait LayoutAlgorithm:
    Send
    + Sync
    + 'static {
    // Required methods
    fn size_that_fits(
        &self,
        subviews: &Subviews<'_>,
        proposal: Proposal,
    ) -> (f64, f64);
    fn place_subviews(
        &self,
        subviews: &Subviews<'_>,
        bounds: Rect,
        proposal: Proposal,
    );
}
Expand description

A layout algorithm.

The two passes are separate methods because SwiftUI runs them separately, and may run the first several times — once per candidate size — before running the second. A layout that placed children while sizing would place them repeatedly.

Implement this on a type when the layout has parameters or state:

struct Cascade { step: f64 }

impl LayoutAlgorithm for Cascade {
    fn size_that_fits(&self, subviews: &Subviews<'_>, _: Proposal) -> (f64, f64) {
        let n = subviews.len() as f64;
        (n * self.step + 60.0, n * self.step + 20.0)
    }
    fn place_subviews(&self, subviews: &Subviews<'_>, bounds: Rect, _: Proposal) {
        for i in 0..subviews.len() {
            let d = i as f64 * self.step;
            subviews.place(i, bounds.x + d, bounds.y + d);
        }
    }
}

A pair of closures implements it too, through FnLayout, so the simple case stays a call rather than a type.

Required Methods§

Source

fn size_that_fits( &self, subviews: &Subviews<'_>, proposal: Proposal, ) -> (f64, f64)

How big this layout wants to be, given what the parent offers.

Source

fn place_subviews( &self, subviews: &Subviews<'_>, bounds: Rect, proposal: Proposal, )

Where each child goes, inside bounds.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl<S, P> LayoutAlgorithm for FnLayout<S, P>
where S: Fn(&Subviews<'_>, Proposal) -> (f64, f64) + Send + Sync + 'static, P: Fn(&Subviews<'_>, Rect, Proposal) + Send + Sync + 'static,