我正在使用 SwiftUI 做一个基于 map 的应用程序,我需要通过向上/向下拖动来更改模态卡片的高度(这是 map 信息所在的 View ),就像在 Apple Maps 中一样。
这是我尝试与之交互的高度的卡片的屏幕截图
/image/mZX2m.png
我已经实现了 ZStack
与 RoundedRectangle
并添加了 DragGesture()
修饰符。
ZStack(alignment: .top){
RoundedRectangle(cornerRadius: 16.0)
.frame(height:currentHeight)
Text("Card")
.font(.title)
.fontWeight(.bold)
.foregroundColor(Color.white)
.multilineTextAlignment(.center)
.padding(.top)
}.gesture(DragGesture()
.onChanged { value in
if (self.currentHeight + value.predictedEndLocation.y - value.startLocation.y > UIScreen.main.bounds.height) {
self.currentHeight = UIScreen.main.bounds.height
} else {
self.currentHeight += value.predictedEndLocation.y - value.startLocation.y
}
}
.onEnded { value in
if (self.currentHeight + value.predictedEndLocation.y - value.startLocation.y > UIScreen.main.bounds.height) {
self.currentHeight = UIScreen.main.bounds.height
} else {
self.currentHeight += value.predictedEndLocation.y - value.startLocation.y
}
})
第一个问题是向上拖动,卡片超过了屏幕高度,我检查 UIScreen 边界高度以防止高度大于屏幕,但是计算存在更多问题,卡片的高度很快就会变得模棱两可,它不想拖累。
我从未使用过手势识别器。你能告诉我正确的计算方法吗?
谢谢!
最佳答案
这是一种方法(下面的代码中有一些有用的注释)
struct TestResizingCard: 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)
Text("Card")
.font(.title)
.fontWeight(.bold)
.foregroundColor(Color.white)
.multilineTextAlignment(.center)
.padding(.top)
}
}
}
struct TestResizingCard_Previews: PreviewProvider {
static var previews: some View {
TestResizingCard()
}
}
关于ios - 在 SwiftUI 中使用 DragGesture() 计算的高度不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59445236/