swift - SwiftUI:防止 Image() 将视图矩形扩展到屏幕边界之外
问题描述
我想要达到的目标
我正在尝试创建一个 SwiftUI 视图,其中图像应该扩展整个屏幕(edgesIgnoringSafeArea(.all)
),然后在其上覆盖一个视图,该视图也填充整个屏幕,但尊重安全区域。
我试过的
这是我的代码,接近:
struct Overlay: View {
var body: some View {
VStack {
HStack {
EmptyView()
Spacer()
Text("My top/right aligned view.")
.padding()
.background(Color.red)
}
Spacer()
HStack {
Text("My bottom view")
.padding()
.background(Color.pink)
}
}
}
}
struct Overlay_Previews: PreviewProvider {
static var previews: some View {
ZStack {
Image(uiImage: UIImage(named: "background")!)
.resizable()
.edgesIgnoringSafeArea(.all)
.aspectRatio(contentMode: .fill)
Overlay()
}
}
}
问题和经过测试的解决方案
问题是图像没有像看起来那样被剪裁,因此它将父视图扩展为大于屏幕宽度的宽度,然后使右上角对齐的红色文本框浮出屏幕(见图)。
我尝试.clipped()
在各个地方使用,但没有运气。如果可能的话,我最好避免使用GeometryReader
。
问:如何让图像视图只填满屏幕?
解决方案
在ZStack拾取越界Image之前,您必须限制其帧大小,以避免ZStack增长,从而导致Overlay偏离位置。
编辑: aheze 用他的答案展示了一种GeometryReader
通过将withImage
放入背景来Overlay()
使用的方法.background(Image()..)
。这完全避免了和的使用,ZStack
并且GeometryReader
可能是一种更清洁的解决方案。
基于父视图大小
struct IgnoringEdgeInsetsView2: View {
var body: some View {
ZStack {
GeometryReader { geometry in
Image("smile")
.resizable()
.aspectRatio(contentMode: .fill)
.edgesIgnoringSafeArea(.all)
.frame(maxWidth: geometry.size.width,
maxHeight: geometry.size.height)
}
Overlay()
}
}
}
基于屏幕尺寸
struct IgnoringEdgeInsetsView: View {
var body: some View {
ZStack {
Image("smile-photo")
.resizable()
.aspectRatio(contentMode: .fill)
.edgesIgnoringSafeArea(.all)
.frame(maxWidth: UIScreen.main.bounds.width,
maxHeight: UIScreen.main.bounds.height)
Overlay()
}
}
}
推荐阅读
- sql - ';' 附近的语法不正确
- javascript - 将当前值与 ajax 成功回调的先前值进行比较
- java - 解析Java中连接在一个字符串中的所有json
- android - 如何从 DialogFragment 更改 Activity 的 textView?
- javascript - 正则表达式以任何顺序匹配至少 7 位数字和任意数量的特殊字符的模式
- amazon-web-services - AWS Deep Learning AMI 实例上的训练模型 - 被警告“杀死”
- asp.net - 下载文件是用 IIS 直接在 Chrome 浏览器中打开文件,而不是下载文件
- reactjs - 如何测试 global.i18n.t
- python - Jupyter - 将当前的 ipynb 文件导出到笔记本中的 html
- php - PHP - 如果字符串包含 '<' 或 '>' - strpos()