You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中ScrollView嵌套GeometryReader时矩形无法底部对齐问题

修复SwiftUI中GeometryReader内矩形无法底部对齐的问题

核心原因

  • GeometryReader会自动撑满父视图分配的所有空间,且内部子视图默认对齐到自身左上角。即使外层HStack设置了alignment: .bottom,生效的也只是GeometryReader容器的对齐,容器内部的矩形仍然顶在GeometryReader的顶部,所以最终呈现所有矩形从顶部开始绘制的效果。

修复方法

仅需要在GeometryReader的矩形代码中新增一行frame设置,让矩形撑满GeometryReader高度同时对齐到底部即可:

GeometryReader { geo in
    Rectangle()
        .fill( geo.frame(in: .global).maxX > 100 && 250 > geo.frame(in: .global).maxX  ? Color.red : Color.gray)
        .frame(width: 5, height: CGFloat(sample))
        .frame(maxHeight: .infinity, alignment: .bottom) // 新增这行即可解决对齐问题
}

可选优化

你当前使用的ForEach(samples, id: \.self)会在数组有重复数值时出现布局异常,建议替换为基于索引的唯一标识:

ForEach(Array(samples.enumerated()), id: \.offset) { index, sample in
    // 原有内部代码
}

完整修改后代码

import SwiftUI

struct Scrollview1: View {
    let samples = [106, 77, 53, 15, 83, 80, 63, 43, 80, 81, 66, 75, 78, 57, 18, 73, 80, 70, 27, 82, 83, 70, 66, 78, 50, 30, 13, 77, 67, 40, 12, 76, 73, 73, 77, 63, 42, 12, 88, 77, 46, 14, 90, 83, 73, 79, 73, 34, 14, 87, 78, 53, 37, 79, 75, 19, 86, 74, 45, 14, 79, 81, 46, 14, 82, 76, 44, 69, 70, 37, 13, 80, 81, 48, 15, 76, 79, 41, 76, 75, 49, 26, 79, 78, 57, 18, 79]
    
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            VStack (spacing: 3) {
                HStack (alignment: .bottom , spacing: 1) {
                    ForEach(Array(samples.enumerated()), id: \.offset) { index, sample in
                        GeometryReader { geo in
                            Rectangle()
                                .fill( geo.frame(in: .global).maxX > 100 && 250 > geo.frame(in: .global).maxX  ? Color.red : Color.gray)
                                .frame(width: 5, height: CGFloat(sample))
                                .frame(maxHeight: .infinity, alignment: .bottom)
                        }
                     }
                }
            }
        }
    }
}
struct Scroll_Previews1: PreviewProvider {
    static var previews: some View {
        Scrollview1()
    }
}

你之前的错误运行效果参考:
运行效果示意图

内容的提问来源于stack exchange,提问作者JohnKubik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:15:04