作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一张图片要放在现有 View 上。它左对齐/领先,但我希望它居中在屏幕上(或鲑鱼色区域)。
这是我的代码:
struct LeaderBoard: View {
@State var shouldDisplayOverLay = true
var body: some View {
ZStack {
VStack(alignment: .center) {
Text("Daily Dashboard")
.font(.subheadline)
Color.darkSalmon
Spacer()
HStack {
Text("Exercise")
Text("Sleep (in hours):")
Text("Weight") // red if lower more than a pound, yellow if less than pound, green if same or higher
}
.font(.caption)
Spacer()
}
Image("Leader-1024")
.resizable()
.scaledToFit()
.modifier(InsetViewModifier())
}
}
}
struct InsetViewModifier: ViewModifier {
func body(content: Content) -> some View {
GeometryReader { proxy in
content
.frame(width: proxy.size.width * 0.8, height: proxy.size.height * 0.8, alignment: .center)
}
}
}
最佳答案
GeometyReader
没有自己的对齐方式,所以解决方案可以是在修改器中嵌入一些堆栈(因为它们都默认具有 .center
对齐方式):
struct InsetViewModifier: ViewModifier {
func body(content: Content) -> some View {
GeometryReader { proxy in
VStack {
content
.frame(width: proxy.size.width * 0.8, height: proxy.size.height * 0.8, alignment: .center)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
和一些复制的演示
关于SwiftUI:如何在父 View 的中心叠加图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64730123/
我是一名优秀的程序员,十分优秀!