import SwiftUI /// 固定 frame:宽高都是硬性提议,内容被放在这个尺寸里。 public struct FixedFrame: View { public init() {} public var body: some View { Rectangle() .fill(.blue) .frame(width: 100, height: 40) } } /// 上限 frame:内容小就保持小,只有内容想更大时才被限制。 public struct BoundedFrame: View { public init() {} public var body: some View { Rectangle() .fill(.blue) .frame(width: 10, height: 10) .frame(maxWidth: 100, maxHeight: 40) } } /// Spacer 只在有剩余空间时扩张。 public struct SpacerRow: View { public let width: CGFloat? public init(width: CGFloat?) { self.width = width } public var body: some View { HStack(spacing: 0) { Rectangle().fill(.blue).frame(width: 20, height: 10) Spacer(minLength: 0) Rectangle().fill(.red).frame(width: 20, height: 10) } .frame(width: width, height: 10) } } /// 同样的窄 frame:默认截断,`fixedSize` 允许换行变高。 public struct WrappingText: View { public let fixed: Bool public let text: String public init(fixed: Bool, text: String = "layout proposal wraps here") { self.fixed = fixed self.text = text } public var body: some View { let label = Text(text).font(.system(size: 13)) Group { if fixed { label.fixedSize(horizontal: false, vertical: true) } else { label.lineLimit(1) } } .frame(width: 90, alignment: .leading) } } /// GeometryReader 会占满父视图给的提议尺寸。 public struct GreedyReader: View { public init() {} public var body: some View { GeometryReader { _ in Color.clear } .background(Color.blue.opacity(0.2)) } } /// 对齐方式影响子视图在交叉轴上的位置,不影响尺寸。 public struct AlignedRow: View { public init() {} public var body: some View { HStack(alignment: .top, spacing: 8) { Rectangle().fill(.blue).frame(width: 30, height: 50) Rectangle().fill(.red).frame(width: 30, height: 20) } .frame(height: 50, alignment: .top) } } /// 截图用:把几种 frame 放在一起,边框可视化提议结果。 public struct LayoutBoard: View { public init() {} public var body: some View { VStack(alignment: .leading, spacing: 12) { row("frame(width: 100, height: 40)") { FixedFrame() } row("frame(maxWidth: 100, maxHeight: 40)") { BoundedFrame() } row("Spacer + frame(width: 160)") { SpacerRow(width: 160) } } .padding(16) .background(Color.white) } private func row(_ title: String, @ViewBuilder content: () -> some View) -> some View { VStack(alignment: .leading, spacing: 4) { content() .border(.quaternary) Text(title) .font(.system(size: 11, design: .monospaced)) .foregroundStyle(.secondary) } } } /// 截图用:截断与换行的对照。 public struct WrapComparison: View { public init() {} public var body: some View { HStack(alignment: .top, spacing: 16) { VStack(alignment: .leading, spacing: 4) { WrappingText(fixed: false).border(.quaternary) Text("默认:截断").font(.system(size: 11, design: .monospaced)) } VStack(alignment: .leading, spacing: 4) { WrappingText(fixed: true).border(.quaternary) Text("fixedSize:换行").font(.system(size: 11, design: .monospaced)) } } .padding(16) .background(Color.white) } }