我有以下示例:
import SwiftUI
struct TestSO: View {
@State var cards = [
Card(title: "short title text", subtitle: "short title example"),
Card(title: "medium title text text text text text", subtitle: "medium title example"),
Card(title: "long title text text text text text text text text text text text text text text text text text",
subtitle: "long title example"),
Card(title: "medium title text text text text text", subtitle: "medium title example"),
Card(title: "short title text", subtitle: "short title example"),
]
@State var showDetails = false
var body: some View {
NavigationView {
ScrollView {
VStack {
ForEach(cards.indices) { index in
GeometryReader { reader in
CardView(showDetails: self.$showDetails, card: self.cards[index])
.offset(y: self.showDetails ? -reader.frame(in: .global).minY : 0)
.onTapGesture {
self.showDetails.toggle()
self.cards[index].showDetails.toggle()
}
}.frame(height: self.showDetails ? UIScreen.main.bounds.height : 80, alignment: .center)
}
}
}.navigationBarTitle("Content", displayMode: .large)
}
}
}
struct CardView : View {
@Binding var showDetails : Bool
var card : Card
var body: some View {
VStack(alignment: .leading){
HStack{
Text(card.subtitle).padding([.horizontal, .top]).fixedSize(horizontal: false, vertical: true)
Spacer()
}
Text(card.title).fontWeight(Font.Weight.bold).padding([.horizontal, .bottom]).fixedSize(horizontal: false, vertical: true)
if(card.showDetails && showDetails) {
Spacer()
}
}
.background(Color.white)
.cornerRadius(16)
.shadow(radius: 12)
.padding()
.opacity(showDetails && card.showDetails ? 1 : (!showDetails ? 1 : 0))
}
}
struct Card : Identifiable{
var id = UUID()
var title : String
var subtitle : String
var showDetails : Bool = false
}
这是一个卡片列表,如果用户点击它就会展开。这里的问题是.frame(height: self.showDetails ? UIScreen.main.bounds.height : 80, alignment: .center)
线。根据 Card-Object 的标题或副标题有多少文本,CardView 必须小于或大于 80。我需要计算高度并使用它而不是固定的 80。
它的外观:
知道如何为 CardView 子级使用具有可变高度的 GeometryReader 吗?
提前致谢!