欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ScrollView中使用Delegate 滚动 UIKit的UIScrollView转化为在SwiftUI中使用

程序员文章站 2024-03-24 12:03:40
...

2019年8月26日

用SWiftUI的ScrollView设计界面,发现该控件没有实现Delegate系列回掉接口,因此需要将UIKit中的UIScrollView继承到SwiftUI的View上面来显示,最简单的转化代码如下所示:

 

import SwiftUI
import UIKit
// in swiftui view file, use like this, it will contruct a scroll view
//LegacyScrollView()

struct LegacyScrollView : UIViewRepresentable {
    // any data state, like @State/@Binding/etc, if needed
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    func makeUIView(context: Context) -> UIScrollView {
        let control = UIScrollView()
        control.refreshControl = UIRefreshControl()
        control.refreshControl?.addTarget(context.coordinator, action:
            #selector(Coordinator.handleRefreshControl),
                                          for: .valueChanged)

        control.delegate = context.coordinator
        
        // Simply to give some content to see in the app
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
        label.text = "Scroll View Content"
        control.addSubview(label)

        return control
    }
    func updateUIView(_ uiView: UIScrollView, context: Context) {
        // code to update scroll view from view state, if needed
    }

    class Coordinator: NSObject, UIScrollViewDelegate{
        var control: LegacyScrollView

        init(_ control: LegacyScrollView) {
            self.control = control
        }
        @objc func handleRefreshControl(sender: UIRefreshControl) {
            // handle the refresh event
            sender.endRefreshing()
        }
        @objc func scrollViewWillBeginDragging(_ scrollView: UIScrollView){
        }
        @objc func scrollViewDidScroll(_ scrollView: UIScrollView){
        }
    }
}