6

What is the best way to deal with SwiftUI is re-rendering an entire view that is moved using an DragGesture and the .offset() modifier: MyView().offset(x: drag.translation.width)?

As soon as MyView() is a very large view, containing a huge amount of complex sub-views, the drag starts to become less and less smooth which is obviously because SwiftUI is re-rendering the entire view each time it is moved which also causes all the descendant views to be redrawn and so on.

Is using the .offset() modifier not feasable when moving large views? is there any alternative approach? So far, using a DragGewture and the offset modifier (or position in some cases) as described here seems to be the common way.

Leo
  • 1,508
  • 13
  • 27
  • maybe using a transform in the likes of CGAffineTransform ? – Nicolas Manzini Apr 29 '21 at 09:40
  • thx, but why would that prevent swift from re-drawing the view? I tried it using `.transformEffect(.init(translationX: pos + drag, y: 0))` but that didn't solve it. – Leo May 01 '21 at 14:50
  • it was just a wild guess, I remember that transform was either faster or slower than changing the frame of an uiview back in 2011 – Nicolas Manzini May 02 '21 at 08:36
  • yah I also find it reasonable since e.g. scaleEffect with a huge factor result sin a blurry view so I thought maybe it just scales it up without re-rendering. But sadly this is not the solution. Is there maybe a way to temporarly disable re-rendering views in SwiftUI? – Leo May 02 '21 at 09:08
  • I have absolutely no idea. I believe not as the purpose of swiftUI is to re-render asap... – Nicolas Manzini May 02 '21 at 11:59
  • 2
    however you can create a bitmap image of the element you are dragging then hide the view, drag the image and on drag end replace the image by the view with the new coordinates. view renderInContext in a UIImageBitmapContextCreate or something alike – Nicolas Manzini May 02 '21 at 12:01
  • awww nice, that made the trick! Exchanging the view with the rendered image happens seamlessly in SwiftUI, and dragging as smooth as it could be. – Leo May 03 '21 at 13:25
  • 1
    For later reference: how to capture a a view as an image in SwiftUI is well explained here: https://www.hackingwithswift.com/quick-start/swiftui/how-to-convert-a-swiftui-view-to-an-image – Leo May 03 '21 at 13:26

0 Answers0