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

iOS 14兼容适配:解决background(alignment:content:)版本报错问题

适配iOS 14的View尺寸获取方案

问题出在background方法的版本兼容上——iOS 15才支持闭包形式的background(alignment:content:),iOS 14只能使用直接传入View实例的background(_:alignment:)重载方法。

修改peekSize方法即可解决,完整代码如下:

struct SizeKey : PreferenceKey
{
    static var defaultValue: CGSize = .zero

    static func reduce(value _: inout CGSize, nextValue _: () -> CGSize) {}
}

extension View
{
    func peekSize(_ size: Binding<CGSize>) -> some View
    {
        // 替换iOS15+的闭包形式background,改用iOS14支持的直接传View的方式
        background(
            GeometryReader
            { geometry in
                Color.clear
                    .preference(key: SizeKey.self, value: geometry.size)
            }
        )
        .onPreferenceChange(SizeKey.self)
        { value in
            size.wrappedValue = value
        }
    }
}

使用方式和之前完全一致,无需改动:

@State var textSize = CGSize.zero

// ...

ScrollView
{
    Text("The quick brown fox jumped over the lazy dog. How vexingly quick daft zebras jump! Pack my box with five dozen liquor jugs. ...")
        .peekSize($textSize)
}
.frame(maxHeight: textSize.height)

修改后代码可同时在iOS 14及iOS 15+系统上正常运行。

内容的提问来源于stack exchange,提问作者meaning-matters

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:47:37