我是 SwiftUI 新手。我正在尝试创建一个类似心形卡片的视图,但无法将心形和字母的 vStack 放置在矩形的右上角(topTrailing)。
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 5.0)
.fill(.white)
.stroke(.gray, style: StrokeStyle(lineWidth: 2.0))
.frame(width: 100, height: 150)
.shadow(color: Color(.black).opacity(0.3), radius: 5)
VStack(spacing: 0) {
Text("A")
.font(.callout)
Image(systemName: "heart.fill")
.resizable()
.frame(width: 10, height: 10)
}.frame(alignment: .topTrailing)
}
}
有人可以帮忙吗。
如果你想告诉ZStack对齐它的子视图,你必须使用ZStack对齐属性,比如:
ZStack(alignment: topLeading) {
...
}
您可以尝试这种替代方法:
var body: some View {
RoundedRectangle(cornerRadius: 5.0)
.fill(.white)
.stroke(.gray, style: StrokeStyle(lineWidth: 2.0))
.frame(width: 100, height: 150)
.shadow(color: Color(.black).opacity(0.3), radius: 5)
.overlay(alignment: .topLeading) {
VStack(spacing: 0) {
Text("A")
.font(.callout)
Image(systemName: "heart.fill")
.resizable()
.frame(width: 10, height: 10)
}
.padding(5)
}
.overlay(alignment: .bottomTrailing) {
VStack(spacing: 0) {
Text("A")
.font(.callout)
Image(systemName: "heart.fill")
.resizable()
.frame(width: 10, height: 10)
}
.scaleEffect(CGSize(width: 1, height: -1)) //<- make the view up side down
.padding(5)
}
}
输出:
你们非常接近!但是,当您将
.frame(alignment: .topTrailing)
应用于 VStack
时,它所做的只是将 VStack
的内容对齐在相同大小的框架内。由于内容已经填满框架,因此没有什么区别。
通过这些更改,它可以正常工作:
将用于设置卡片大小的
.frame
修改器从 RoundedRectangle
移动到包含所有内容的
ZStack
。
maxWidth: .infinity, maxHeight: .infinity
添加到
.frame
上设置的
VStack
修改器,以便框架扩展以使用所有可用空间。
VStack
上添加一些填充。
ZStack {
RoundedRectangle(cornerRadius: 5.0)
// as before, but without .frame
VStack(spacing: 0) {
// as before
}
.padding(8) // <- ADDED
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing) // <- maxWidth and maxHeight added
}
.frame(width: 100, height: 150) // <- moved from RoundedRectangle
所以它的作用是将 ZStack
的大小固定为卡片大小。 A
RoundedRectangle
是贪婪的,因此它会扩展以填充相同的空间。
.frame
上的
VStack
修饰符现在会使其扩展到
ZStack
的大小,并且
alignment
参数会按照您的预期对齐内容。