我有點難過構建一個包含串列的可拖動幻燈片。受這篇文章的啟發,下面是我所擁有的 MRE。
import SwiftUI
struct ContentView: View {
static let kMinHeight: CGFloat = 100.0
@State var currentHeight: CGFloat = kMinHeight // << any initial
var body: some View {
GeometryReader { g in // << for top container height limit
ZStack(alignment: .bottom) {
Rectangle().fill(Color.yellow) // << just for demo
self.card()
.gesture(DragGesture()
.onChanged { value in
// as card is at bottom the offset is reversed
let newHeight = self.currentHeight - (value.location.y - value.startLocation.y)
if newHeight > Self.kMinHeight && newHeight < g.size.height {
self.currentHeight = newHeight
}
})
}
}
}
func card() -> some View {
ZStack(alignment: .top){
RoundedRectangle(cornerRadius: 16.0)
.frame(height:currentHeight)
VStack{
RoundedRectangle(cornerRadius: Constants.radius)
.fill(Color.white)
.frame(
width: Constants.indicatorWidth,
height: Constants.indicatorHeight
)
Text("Card")
.font(.title)
.fontWeight(.bold)
.foregroundColor(Color.white)
.multilineTextAlignment(.center)
.padding(.top)
Text("LINE 2")
.foregroundColor(Color.white)
// Uncomment the following lines, and the slides becomes unusable
// List {
// Text("The Fellowship of the Ring")
// Text("The Two Towers")
// Text("The Return of the King")
//}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
使用此示例構建的幻燈片有效,但請注意,我已注釋掉包含串列的幾行。取消注釋這些行后,滑塊將無法使用。
兩個明顯的問題:(1)為什么會這樣,以及(2)關于如何解決它的任何建議?:)
uj5u.com熱心網友回復:
在您的代碼中,您只指定卡片內矩形的高度。如果只有矩形存在,這不是問題。但:
這里的麻煩在于它List包裝了它自己的滾動行為,因此它會擴展以占用它可以占用的所有空間。與其只限制卡片內的矩形,不如將卡片的高度限制為currentHeight:
func card() -> some View {
ZStack(alignment: .top){
RoundedRectangle(cornerRadius: 16.0)
VStack{
RoundedRectangle(cornerRadius: 10)
.fill(Color.white)
.frame(
width: 20,
height: 20
)
Text("Card")
.font(.title)
.fontWeight(.bold)
.foregroundColor(Color.white)
.multilineTextAlignment(.center)
.padding(.top)
Text("LINE 2")
.foregroundColor(Color.white)
// Uncomment the following lines, and the slides becomes unusable
List {
Text("The Fellowship of the Ring")
Text("The Two Towers")
Text("The Return of the King")
}
}
}
.frame(maxHeight: currentHeight) // This line
}
uj5u.com熱心網友回復:
您遇到的問題List是貪婪的觀點。它占用了它可能占用的所有空間,這讓你的身高變得不正常。簡單的解決方案是把它放在一個框架中,當卡一直向下時為零。由于我們有這些值,我們需要做的就是:
List {
Text("The Fellowship of the Ring")
Text("The Two Towers")
Text("The Return of the King")
}
.frame(height: currentHeight - DraggableSlides.kMinHeight)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448438.html
