[英]SwiftUI strange behaviour with HStack
正如標題所說,我無法理解布局中的問題出在哪里。
我創建了一個名為SmallCard
的簡單視圖
struct SmallCard: View {
var image: Image
var title: String
var body: some View {
VStack(spacing: 0.0) {
self.image
.resizable()
.scaledToFit()
ZStack {
Color.white
VStack(alignment: .leading) {
Text(self.title)
.padding([.vertical])
}
}
}
.rounded(radius: 10)
.shadow(radius: 2.0)
}
}
struct SmallCard_Previews: PreviewProvider {
static var previews: some View {
SmallCard(image: Image("img02"), title: "Card title")
}
}
有了這個結果
然后我創建了另一個名為TestExploreCards
視圖
struct TestExploreCards: View {
var body: some View {
ScrollView {
HStack(alignment: .center, spacing: 8.0) {
SmallCard(image: Image("img04"),
title: "Card title 01")
SmallCard(image: Image("img05"),
title: "Card title 03")
}
}
}
}
struct TestExploreCards_Previews: PreviewProvider {
static var previews: some View {
TestExploreCards()
}
}
我放兩張SmallCard
的地方但我得到了
正如您在SmallCard
預覽Image
中看到的那樣,圖像的寬度與下面的視圖相同,但是當我將HStack
與另一個SmallCard
實例一起放入時,它不是。 我不知道錯誤在哪里:\
需要明確的是, rounded
是一個View
擴展
extension View {
func rounded(radius: CGFloat = 25.0) -> some View {
self.clipShape(RoundedRectangle(cornerRadius: radius, style: .continuous))
}
}
HStack 填充了寬度,但圖像試圖按其比例適應內容。
這是修改后的代碼:
struct SmallCard: View {
var image: Image
var title: String
var body: some View {
VStack(spacing: 0.0) {
self.image
.resizable()
.scaledToFill()
VStack(alignment: .leading) {
Text(self.title)
.padding(.vertical)
.frame(maxWidth: .infinity)
}
.background(
Color.white
)
}
.frame(minHeight: 250.0)
.rounded(radius: 10)
.fixedSize(horizontal: false, vertical: true)
.shadow(radius: 2.0)
}
}
struct TestExploreCards: View {
var body: some View {
ScrollView {
HStack(alignment: .center, spacing: 8.0) {
SmallCard(image: Image("img04"),
title: "Card title 01")
SmallCard(image: Image("img05"),
title: "Card title 03")
}
}
.padding()
}
}
struct TestExploreCards_Previews: PreviewProvider {
static var previews: some View {
TestExploreCards()
}
}
extension View {
func rounded(radius: CGFloat = 25.0) -> some View {
self.clipShape(RoundedRectangle(cornerRadius: radius))
}
}
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.