swiftui Divider 拖动及其抖动解决

21 阅读1分钟

swiftui Divider 拖动及其抖动解决

Divider 拖动功能:

divider作为分割线,有时会需要可以拖动.修改方式有两种

  1. 当左边有图形时,修改左边的view的数据。
  2. 也可以只是修改本身的数据

修改本身数据就是修改offset的方法,这里不写。

修改左边的view的数据

重要: DragGesture(minimumDistance: 0,coordinateSpace: .global)

其中 coordinateSpace 如果改为local会导致抖动经常发生,原因是拖动的时候value的location实际是不稳定的,即使是很微小的拖动,也会导致location的数据不同这里就是抖动的问题。因为参照物一直在改变。

而global就可以很好的缓解,实际还是会发生,但是发生在快速的移动中。参照物就是屏幕。

相关代码:

struct TerminalView: View {

    @State var width:CGFloat = 200.0

    @State var startWidth = 200.0


    var body: some View {

        GeometryReader{ gProxy in

            HStack(){

                AView().frame(width: width,height: gProxy.size.height)

                Divider()

                    .frame(width:  10)

                    .background(.pink)

                    .gesture(

                        DragGesture(minimumDistance: 0,coordinateSpace: .global)

                            .onChanged { value in

                                let newWidth = startWidth + value.translation.width
                                
                                width = max(80, newWidth) // 限制80
                                

                            }

                            .onEnded { value **in******

                                startWidth = width

                            }

                    )

                BView().frame(height: gProxy.size.height)

            }

           

        }        

    }