本篇文章主要內容是Hosting+Representable,但我們首先會講解一下在iOS14中,ScrollView新增的一個功能。
ScrollViewProxy & ScrollViewReader
在iOS14中,ScrollView新增了一個ScrollViewProxy和ScrollViewReader。
public struct ScrollViewProxy {
public func scrollTo<ID>(_ id: ID, anchor: UnitPoint? = nil) where ID : Hashable
}
@frozen public struct ScrollViewReader<Content> : View where Content : View {
public var content: (ScrollViewProxy) -> Content
@inlinable public init(@ViewBuilder content: @escaping (ScrollViewProxy) -> Content)
/// The content and behavior of the view.
public var body: some View { get }
public typealias Body = some View
}
- ScrollViewReader需要寫在ScrollView內部,其目的是獲取ScrollViewProxy
- ScrollViewProxy中有一個方法,能夠讓ScrollView滾動到某個id的位置
仔細觀察上圖,可以發現,點擊最左邊的按鈕,確實能夠讓ScrollView滾動到某個指定的位置,scrollTo<ID>(_ id: ID, anchor: UnitPoint? = nil) where ID : Hashable
函數中,有一個參數叫anchor,當其值為nil時,系統會自動計算出滾動到該位置最短的距離,當不為nil時區別是:
-
leading
表示滾動到與ScrollView左對齊 -
.center
表示滾動到ScrollView的中間 -
.trailing
表示滾動到與ScrollView右對齊
用起來非常簡單,但是值得注意的是,按鈕必須在ScrollView中才行。代碼如下:
struct Example1: View {
var body: some View {
ScrollView(.horizontal) {
ScrollViewReader { scrollViewProxy in
LazyHStack(spacing: 10) {
...
ForEach(0..<20) { index in
Text("\(index)")
.frame(width: 100, height: 240)
.background(index == 6 ? Color.green : Color.orange.opacity(0.5))
.cornerRadius(3.0)
}
}
.padding(.horizontal, 10)
}
}
.frame(height: 300, alignment: .center)
}
}
ScrollViewRepresentable
上邊提到的新增的這個功能只能算是一個非常小的功能,在UIKit中,ScrollView有十分豐富的功能,我們知道,通過ScrollViewRepresentable可以讓我們直接使用UIKit中的View,代碼類似于:
struct Example2: View {
var body: some View {
ScrollViewRepresentable()
.frame(width: 200, height: 100)
}
struct ScrollViewRepresentable: UIViewRepresentable {
func makeUIView(context: Context) -> UIScrollView {
let scrollView = UIScrollView()
scrollView.backgroundColor = UIColor.green
return scrollView
}
func updateUIView(_ uiView: UIScrollView, context: Context) {}
}
}
在這種情況下,只能讓我們訪問到UIScrollView,但是如果在其上邊添加SwiftUI中的View就做不到了。因此這種方案pass掉。
Hosting+Representable
所謂的Hosting指的是UIHostingController<Content>,而Representable則指的是UIViewControllerRepresentable,只需把這兩者結合起來,能夠獲取強大的能力。
那么UIHostingController是什么呢?先給大家看一張圖:
很明顯,它就是SwiftUI和UIKit中的一個橋梁,系統會把SwiftUI中的View翻譯成UIKit中的View。我們最終的目的是實現下邊兩張圖的效果:
- 監聽當前滾動的offset
- 滾動到指定的offset處
class MyScrollViewUIHostingController<Content>: UIHostingController<Content> where Content: View {
var offset: Binding<CGFloat>
let isOffsetX: Bool
var showed = false
var sv: UIScrollView?
init(offset: Binding<CGFloat>, isOffsetX: Bool, rootView: Content) {
self.offset = offset
self.isOffsetX = isOffsetX
super.init(rootView: rootView)
}
@objc dynamic required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidAppear(_ animated: Bool) {
/// 保證設置一次監聽
if showed {
return
}
showed = true
/// 查找UIScrollView
sv = findScrollView(in: view)
/// 設置監聽
sv?.addObserver(self,
forKeyPath: #keyPath(UIScrollView.contentOffset),
options: [.old, .new],
context: nil)
/// 滾動到指定位置
scroll(to: offset.wrappedValue, animated: false)
super.viewDidAppear(animated)
}
func scroll(to position: CGFloat, animated: Bool = true) {
if let s = sv {
if position != (self.isOffsetX ? s.contentOffset.x : s.contentOffset.y) {
let offset = self.isOffsetX ? CGPoint(x: position, y: 0) : CGPoint(x: 0, y: position)
sv?.setContentOffset(offset, animated: animated)
}
}
}
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(UIScrollView.contentOffset) {
if let s = self.sv {
DispatchQueue.main.async {
self.offset.wrappedValue = self.isOffsetX ? s.contentOffset.x : s.contentOffset.y
}
}
}
}
func findScrollView(in view: UIView?) -> UIScrollView? {
if view?.isKind(of: UIScrollView.self) ?? false {
return view as? UIScrollView
}
for subview in view?.subviews ?? [] {
if let sv = findScrollView(in: subview) {
return sv
}
}
return nil
}
}
MyScrollViewUIHostingController中,可以直接訪問到UIScrollView,并且把傳過來的Content設置為rootView,上邊這段代碼還是非常簡單的。
struct MyScrollViewControllerRepresentable<Content>: UIViewControllerRepresentable where Content: View {
var offset: Binding<CGFloat>
let isOffsetX: Bool
var content: Content
func makeUIViewController(context: Context) -> MyScrollViewUIHostingController<Content> {
MyScrollViewUIHostingController(offset: offset, isOffsetX:isOffsetX, rootView: content)
}
func updateUIViewController(_ uiViewController: MyScrollViewUIHostingController<Content>, context: Context) {
uiViewController.scroll(to: offset.wrappedValue, animated: true)
}
}
MyScrollViewControllerRepresentable實現了UIViewControllerRepresentable協議,因此可以直接在SwiftUI的View中創建。
extension View {
func scrollOffsetX(_ offsetX: Binding<CGFloat>) -> some View {
return MyScrollViewControllerRepresentable(offset: offsetX, isOffsetX: true, content: self)
}
}
extension View {
func scrollOffsetY(_ offsetY: Binding<CGFloat>) -> some View {
return MyScrollViewControllerRepresentable(offset: offsetY, isOffsetX: false, content: self)
}
}
最后,我們創建了兩個View的extension,像下邊的代碼一樣使用:
ScrollView(.horizontal) {
...
}
.scrollOffsetX(self.$offsetX)
ScrollView(.vertical) {
...
.scrollOffsetY(self.$offsetY)
總結
當我們遇到SwiftUI提供的功能不夠用的時候,我們可以考慮上邊用到的這種解決方案,能夠為我們提供一個不錯的思路。
我已經把該功能單獨地抽離出來了,代碼倉庫地址為https://github.com/agelessman/SwiftUI_ScrollView_Offset
本篇文章的示例代碼在此處可以訪問:https://gist.github.com/agelessman/3bf1d4f4d7fb24495972ba962777874f
SwiftUI集合:FuckingSwiftUI