在以下示例中,视图相对于图像放置,在这种情况下位于右下角:
struct RelativePositionExampleView: View {
var body: some View {
Image("cookies")
.resizable()
.aspectRatio(contentMode: .fit)
.overlay(
GeometryReader { geometry in
Text("Hello")
.background(Color.red)
.position(x: geometry.size.width * 1.0, y: geometry.size.height * 1.0)
}
)
}
}
.position的“锚点”是“文本”视图的中心:
我尝试使用Change Button Anchor Point SwiftUI中所述的对齐指南,但这并没有解决问题。
在这种情况下,是否可以表达“基于上/左或下/右角的位置”? (不是基于Spacer的-位置不必一定在拐角处,它可以是宽度f的30%,即相对于所定位视图的左边缘的30%)。
答案 0 :(得分:0)
如果目标是将文本放置在图像角落,那么有一种更简单的解决方案。
var body: some View {
Image("cookies")
.resizable()
.aspectRatio(contentMode: .fit)
.overlay(
ZStack {
Text("Hello")
}.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
)
}
答案 1 :(得分:0)
这是一种非常通用的方式,可以根据您的喜好相对放置叠加视图。在Playground中尝试。
import SwiftUI
import PlaygroundSupport
extension View {
func overlay<V: View>(alignment: Alignment, relativePos: UnitPoint = .center, _ other: V) -> some View {
self
.alignmentGuide(alignment.horizontal, computeValue: { $0.width * relativePos.x })
.alignmentGuide(alignment.vertical, computeValue: { $0.height * relativePos.y })
.overlay(other, alignment: alignment)
}
}
struct ContentView: View {
var body: some View {
Circle()
.foregroundColor(.yellow)
.frame(width: 200, height: 200)
.overlay(alignment: .center, relativePos: UnitPoint(x: 0.3, y: 0.3), Capsule().fill(Color.green).frame(width: 40, height: 20))
.overlay(alignment: .center, relativePos: UnitPoint(x: 0.7, y: 0.3), Capsule().fill(Color.green).frame(width: 40, height: 20))
.overlay(alignment: .center, relativePos: UnitPoint(x: 0.5, y: 0.75), Text("Hello"))
.overlay(alignment: .center, relativePos: .bottom, Divider())
}
}
PlaygroundPage.current.setLiveView(ContentView())