更改内容偏移时的 Swift ScrollView 动画

问题描述

我正在尝试实现一项功能,以便即使我使用变量更改 ScrollView Carousel 中的页面,滚动效果动画仍然会发生。当我使用滚动功能手动更改页面时,我显然能够获得滚动效果。但是,当我更新来自 NotificationCenter 的页面变量时,页面变量发生了变化,但看不到任何效果。如何将动画添加到此 UIScrollView?

我有以下一段代码

struct Carousel: UIViewRepresentable {
func makeCoordinator() -> Coordinator {
    return Carousel.Coordinator(parent: self)
}

var width: CGFloat
@Binding var page: Int
var height: CGFloat
var data: [Fon]
@Observedobject var viewmodel: Fonviewmodel

func makeUIView(context: Context) -> UIScrollView {
    let total = width * CGFloat(data.count)
    let view = UIScrollView()
    view.isPagingEnabled = true
    view.contentSize = CGSize(width: total,height: 1.0)
    view.bounces = true
    view.showsverticalScrollIndicator = false
    view.showsHorizontalScrollIndicator = false
    view.delegate = context.coordinator
    
    let view1 = UIHostingController(rootView: List(data: self.data,viewmodel: self.viewmodel,page: $page))
    view1.view.frame = CGRect(x: 0,y: 0,width: total,height: self.height)
    view1.view.backgroundColor = .clear
    
    view.addSubview(view1.view)
    return view
}
func updateUIView(_ uiView: UIScrollView,context: Context) {
    
    if self.viewmodel.finished {
        
        //if self.viewmodel.fons.count - 1 != page {self.page += 1} else {page = 0}
        print("page:\(page) and count: \(self.viewmodel.fons.count)")
        
        uiView.contentOffset.x += UIScreen.main.bounds.width
        self.viewmodel.finished = false
        print("scrolling")
    }

    NotificationCenter.default.addobserver(forName: NSNotification.Name("Finish"),object: nil,queue: .main) { (_) in
        self.viewmodel.finished = true
    }
}

class Coordinator: NSObject,uiscrollviewdelegate {
    var parent: Carousel
    
    init(parent: Carousel) {
        self.parent = parent
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        parent.viewmodel.finished = true
        
        let page = Int(scrollView.contentOffset.x / UIScreen.main.bounds.width)
        
        self.parent.page = page
        print(page)
    }
}

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)