Roman Mahotskyi
Roman Mahotskyi

Reputation: 6625

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()
      }
    }
}

Upvotes: 1

Views: 2115

Answers (1)

Raja Kishan
Raja Kishan

Reputation: 18934

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)

Upvotes: 2

Related Questions