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

SwiftUI动态内容视图高度获取及‘ViewHeightKey未找到’报错解决

解决SwiftUI视图高度获取时的"Cannot find 'ViewHeightKey' in scope"错误

错误原因

Swift代码解析遵循从上到下的顺序,你在ContentView中先引用了ViewHeightKey,但这个自定义PreferenceKey的定义放在了ContentView之后,导致编译时无法在当前作用域找到该类型。

修正方案

把ViewHeightKey的定义移到ContentView之前,同时优化视图高度测量逻辑(原代码中把GeometryReader作为子视图会额外占用布局空间,正确做法是用background或overlay挂载测量容器,不影响原有布局):

import SwiftUI

// 先定义PreferenceKey,确保ContentView能找到它
struct ViewHeightKey: PreferenceKey {
    static var defaultValue: CGFloat = 0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

struct ContentView: View {
    @State private var contentHeight: CGFloat = .zero

    var body: some View {
        VStack {
            Text("Dynamic Content")
            // 可添加动态内容触发高度变化,比如按钮切换文本
            Button("切换内容") {
                // 示例逻辑:修改文本长度或添加内容
            }
            Spacer()
        }
        .background(
            GeometryReader { geometry in
                Color.clear.preference(
                    key: ViewHeightKey.self,
                    value: geometry.size.height
                )
            }
        )
        .onPreferenceChange(ViewHeightKey.self) { newHeight in
            contentHeight = newHeight
            print("当前视图高度:\(newHeight)")
        }
        .border(Color.blue) // 可视化边框
        .frame(height: contentHeight) // 根据测量高度设置框架(按需使用)
    }
}

额外说明

  • 若需测量特定子视图高度,只需将background(GeometryReader...)添加到目标子视图上即可。
  • 当视图内容动态变化时,PreferenceKey会自动同步更新高度值,无需手动触发刷新。

内容的提问来源于stack exchange,提问作者János

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:22:30