Cotton code
44 lines · 2.0 KB · SwiftRaw
// A card's picture yields to its writing. Fixed picture heights cannot// reserve a share of a short deck card and also leave room for its footer.import SwiftUIstruct CardBodyLayout: Layout {    var pictureShare: CGFloat    var footGap: CGFloat = 6    static func heights(room: CGFloat, pictureShare: CGFloat, writing: [CGFloat], footGap: CGFloat) -> [CGFloat] {        guard !writing.isEmpty else { return [max(0, room * pictureShare)] }        let gap = min(footGap, max(0, room))        var fitted = writing        // The footer is an action surface. Reserve it before proposing room        // to the writing, even when a short card cannot fit three summary lines.        let footer = min(max(0, room - gap), writing.last!)        fitted[fitted.count - 1] = footer        var left = max(0, room - footer - gap)        for index in fitted.indices.dropLast() {            fitted[index] = min(writing[index], left)            left -= fitted[index]        }        let picture = max(0, min(room * pictureShare, left))        return [picture] + fitted    }    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {        proposal.replacingUnspecifiedDimensions()    }    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {        guard !subviews.isEmpty else { return }        let writing = subviews.dropFirst().map { $0.sizeThatFits(.init(width: bounds.width, height: nil)).height }        let heights = Self.heights(room: bounds.height, pictureShare: pictureShare, writing: writing, footGap: footGap)        var y = bounds.minY        for (index, view) in subviews.enumerated() {            if index == subviews.count - 1, index > 0 {                y = bounds.maxY - heights[index]            }            view.place(at: CGPoint(x: bounds.minX, y: y), anchor: .topLeading,                       proposal: .init(width: bounds.width, height: heights[index]))            y += heights[index]        }    }}