Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

How to change the height of the object by using DragGesture in SwiftUI?

I'm trying to increase the height of the shape by using the "dragger" (rounded grey rectangle) element. I use the DragGesture helper provided by SwiftUI to get the current position of the user finger. Unfortunately, during the drag event content is jumping for some reason.

Could you please help me to find the root cause of the problem?

This is how it looks during the drag event

enter image description here

If I remove Spacer() everything is okay but not what I wanted

enter image description here

This is my code snippets

import SwiftUI

struct ContentView: View {
  
  var body: some View {
    VStack {
      CustomDraggableComponent()
      
      Spacer() // If comment this line the result will be as on the bottom GIF example
    }
}
import SwiftUI

let MIN_HEIGHT = 50

struct CustomDraggableComponent: View {
  @State var height: CGFloat = MIN_HEIGHT
  
  var body: some View {
    VStack {
      Rectangle()
        .fill(Color.red)
        .frame(width: .infinity, height: height)
      
      HStack {
        Spacer()
        Rectangle()
          .fill(Color.gray)
          .frame(width: 100, height: 10)
          .cornerRadius(10)
          .gesture(
            DragGesture()
              .onChanged { value in
                height = value.translation.height + MIN_HEIGHT
              }
          )
        Spacer()
      }
    }
}
question from:https://stackoverflow.com/questions/65846863/how-to-change-the-height-of-the-object-by-using-draggesture-in-swiftui

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The correct calculation is

.gesture(
    DragGesture()
        .onChanged { value in
            height = max(MIN_HEIGHT, height + value.translation.height)
        }
)

Also, remove the infinite width. It's invalid.

.frame(minHeight: 0, maxHeight: height)

or 

.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: height)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...