enter image description here

I'm trying to build a view which can be swiped up and down. I'm not sure why the above behaviour is occurring in my code. The text is kind of jumping/stuttering. I want the view to be draggable while the text is animating without the animation being broken. Am I doing something I'm not supposed to do? Below is my code. Any tips would be highly appreciated.

struct ContentView: View {
    @State var offset : CGFloat = 0
    @State var time: String = "0.0"
    let timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()

    var body: some View {
      VStack {
        Spacer()
        Text(String(time)).contentTransition(.numericText())
          .onReceive(timer) { value in
            withAnimation {
              time = value.timeIntervalSince1970.minuteSecond // I have an extension for this.
            }
          }
        Spacer()
      }
      .frame(maxWidth: .infinity)
      .background(.red)
      .offset(y: offset)
      .gesture(swipeDownGesture)
    }
}

extension ContentView {
  var swipeDownGesture: some Gesture {
    DragGesture()
      .onChanged(onDrag(value:))
      .onEnded(onSwipeDownEnded(value:))
  }

  func onDrag(value: DragGesture.Value){
      let horizontalAmount = value.translation.width
      let verticalAmount = value.translation.height
      let isHorizontalSwipe = abs(horizontalAmount) > abs(verticalAmount)
      let isSwipeDown = verticalAmount > 0
      if isHorizontalSwipe {
        let isSwipeRight = horizontalAmount > 0
        if isSwipeRight {
          // Ignore
        } else {
          // Ignore
        }
      }
      else if isSwipeDown {
        withAnimation {
          offset = value.translation.height
        }
      }
  }

  func onSwipeDownEnded(value: DragGesture.Value){
    withAnimation(.smooth(duration: 0.32, extraBounce: 0.22)) {
      offset = 0
    }
  }
}

推荐答案

看起来,contentTransition与屏幕上文本位置的变化结合在一起并不能很好地工作.

这有助于在Text的基础上增加.drawingGroup():

Text(String(time)).contentTransition(.numericText())
    .onReceive(timer) { value in
        // as before
    }
    .drawingGroup() // <- ADDED

Animation

Ios相关问答推荐

Flutter WebRTC:GetUserMedia()不适用于Safari和IOS设备

如何从ipad获取用户定义的设备名称,IOS版本应大于16在flutter

SWIFT中具有可选返回类型和泛型的网络请求

如何根据SWIFT中的按钮点击更新文本值

无法下载并安装带有Xcode 15.0的iOS 17.0模拟器运行时

视图未更新以在按下按钮时显示另一个视图

执行devicectl:ProcessException时出错:进程异常退出:错误:命令超时超过5.0秒

如何擦除 Swift 中的 Core Graphics Context 绘图?

滚动 swiftUI 列表时,未调用单元格的任务修饰符.怎么修?

如何识别 SwiftUI 中点击的按钮 ID 以使该按钮动画化?

UICollectionView - 水平滚动,水平布局?

UIButton在iOS7中没有显示突出显示

每次运行后,Xcode 6 都会在 iOS8 模拟器中重命名我的应用程序目录.

iOS 中是否有用于自定义振动的 API?

通过touch 传递到下面的 UIViews

用 PC 调试 ipad safari

如何隐藏uitabbar控制器

有什么方法可以加粗 NSString 的一部分?

从故事板导航到其他 Swift 1.2 文件时 Xcode 6.3 崩溃

NSURL 到带有 XCTest 的测试包中的文件路径