热门标签 | HotTags
当前位置:  开发笔记 > IOS > 正文

如何获取SwiftUI视图以完全填充其超级视图?

如何解决《如何获取SwiftUI视图以完全填充其超级视图?》经验,为你挑选了1个好方法。

以下内容应该创建一个Text边界,该边界占据整个屏幕,但似乎什么也没做。

struct ContentView: View {
    var body: some View {
        Text("foo")
            .relativeSize(width: 1.0, height: 1.0)
            .background(Color.red)
    }
}

以下黑客:

extension View {
    /// Causes the view to fill into its superview.
    public func _fill(alignment: Alignment = .center) -> some View {
        GeometryReader { geometry in
            return self.frame(
                width: geometry.size.width,
                height: geometry.size.height,
                alignment: alignment
            )
        }
    }
}

struct ContentView2: View {
    var body: some View {
        Text("foo")
            ._fill()
            .background(Color.red)
    }
}

似乎工作。

这是带有的SwiftUI错误relativeSize,还是我缺少某些东西?



1> rob mayoff..:

You need to watch WWDC 2019 Session 237: Building Custom Views with SwiftUI, because Dave Abrahams discusses this topic, and uses Text in his examples.

To restate briefly what Dave explains in detail:

    The parent (in this case, a root view created by the system and filling the screen) proposes a size to its child.

    The child chooses its own size, consuming as much or as little of the proposed size as it wants.

    The parent positions the child in the parent’s coordinate space based on various parameters including the size chosen by the child.

Thus you cannot force a small Text to fill the screen, because the Text will refuse to consume more space than needed to fit its content.

If you want the red background to fill the screen, you can wrap the Text in an expandable view, force the expandable view to full size, and set the background of the expandable view. This works:

var body: some View {
    ZStack {
        Spacer()
        Text("Hello")
        }
        .background(Color.red)
}

The Spacer accepts whatever size its parent offers, so the ZStack can't shrink down to the size of just the Text.


推荐阅读
author-avatar
hellopc
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有