-
Notifications
You must be signed in to change notification settings - Fork 234
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Optimize SwiftUIWrapperView #320
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,23 +22,23 @@ import SwiftUI | |
/// Consider using the `calendarItemModel` property, defined as an extension on SwiftUI's`View`, to avoid needing to work with | ||
/// this wrapper view directly. | ||
/// e.g. `Text("\(dayNumber)").calendarItemModel` | ||
/// | ||
/// - Warning: Using a SwiftUI view with the calendar will cause `SwiftUIView.HostingController`(s) to be added to the | ||
/// closest view controller in the responder chain in relation to the `CalendarView`. | ||
@available(iOS 13.0, *) | ||
public final class SwiftUIWrapperView<Content: View>: UIView { | ||
|
||
// MARK: Lifecycle | ||
|
||
public init(contentAndID: ContentAndID) { | ||
self.contentAndID = contentAndID | ||
hostingController = HostingController( | ||
rootView: .init(content: contentAndID.content, id: contentAndID.id)) | ||
hostingController = UIHostingController(rootView: AnyView(contentAndID.content)) | ||
hostingController._disableSafeArea = true | ||
|
||
super.init(frame: .zero) | ||
|
||
insetsLayoutMarginsFromSafeArea = false | ||
layoutMargins = .zero | ||
|
||
hostingControllerView.backgroundColor = .clear | ||
addSubview(hostingControllerView) | ||
} | ||
|
||
required init?(coder _: NSCoder) { | ||
|
@@ -47,16 +47,20 @@ public final class SwiftUIWrapperView<Content: View>: UIView { | |
|
||
// MARK: Public | ||
|
||
public override class var layerClass: AnyClass { | ||
CATransformLayer.self | ||
} | ||
|
||
public override var isAccessibilityElement: Bool { | ||
get { false } | ||
set { } | ||
} | ||
|
||
public override func didMoveToWindow() { | ||
super.didMoveToWindow() | ||
|
||
if window != nil { | ||
setUpHostingControllerIfNeeded() | ||
public override var isHidden: Bool { | ||
didSet { | ||
if isHidden { | ||
hostingController.rootView = AnyView(EmptyView()) | ||
} | ||
} | ||
} | ||
|
||
|
@@ -65,7 +69,7 @@ public final class SwiftUIWrapperView<Content: View>: UIView { | |
// modifier. Its first subview's `isUserInteractionEnabled` _does_ appear to be affected by the | ||
// `allowsHitTesting` modifier, enabling us to properly ignore touch handling. | ||
if | ||
let firstSubview = hostingController.view.subviews.first, | ||
let firstSubview = hostingControllerView.subviews.first, | ||
!firstSubview.isUserInteractionEnabled | ||
{ | ||
return false | ||
|
@@ -76,62 +80,42 @@ public final class SwiftUIWrapperView<Content: View>: UIView { | |
|
||
public override func layoutSubviews() { | ||
super.layoutSubviews() | ||
hostingControllerView?.frame = bounds | ||
hostingControllerView.frame = bounds | ||
} | ||
|
||
public override func systemLayoutSizeFitting( | ||
_ targetSize: CGSize, | ||
withHorizontalFittingPriority _: UILayoutPriority, | ||
verticalFittingPriority _: UILayoutPriority) | ||
withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, | ||
verticalFittingPriority: UILayoutPriority) | ||
-> CGSize | ||
{ | ||
hostingController.sizeThatFits(in: targetSize) | ||
hostingControllerView.systemLayoutSizeFitting( | ||
targetSize, | ||
withHorizontalFittingPriority: horizontalFittingPriority, | ||
verticalFittingPriority: verticalFittingPriority) | ||
} | ||
|
||
// MARK: Fileprivate | ||
|
||
fileprivate var contentAndID: ContentAndID { | ||
didSet { | ||
hostingController.rootView = .init(content: contentAndID.content, id: contentAndID.id) | ||
hostingController.rootView = AnyView(contentAndID.content) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I profiled and there was no perf hit from switching to |
||
configureGestureRecognizers() | ||
} | ||
} | ||
|
||
// MARK: Private | ||
|
||
private let hostingController: HostingController<IDWrapperView<Content>> | ||
|
||
private weak var hostingControllerView: UIView? | ||
|
||
private func setUpHostingControllerIfNeeded() { | ||
guard let closestViewController = closestViewController() else { | ||
assertionFailure( | ||
"Could not find a view controller to which the `UIHostingController` could be added.") | ||
return | ||
} | ||
|
||
guard hostingController.parent !== closestViewController else { return } | ||
|
||
if hostingController.parent != nil { | ||
hostingController.willMove(toParent: nil) | ||
hostingController.view.removeFromSuperview() | ||
hostingController.removeFromParent() | ||
hostingController.didMove(toParent: nil) | ||
} | ||
|
||
hostingController.willMove(toParent: closestViewController) | ||
closestViewController.addChild(hostingController) | ||
hostingControllerView = hostingController.view | ||
addSubview(hostingController.view) | ||
hostingController.didMove(toParent: closestViewController) | ||
private let hostingController: UIHostingController<AnyView> | ||
|
||
setNeedsLayout() | ||
private var hostingControllerView: UIView { | ||
hostingController.view | ||
} | ||
|
||
// This allows touches to be passed to `ItemView` even if the SwiftUI `View` has a gesture | ||
// recognizer. | ||
private func configureGestureRecognizers() { | ||
for gestureRecognizer in hostingControllerView?.gestureRecognizers ?? [] { | ||
for gestureRecognizer in hostingControllerView.gestureRecognizers ?? [] { | ||
gestureRecognizer.cancelsTouchesInView = false | ||
} | ||
} | ||
|
@@ -167,13 +151,13 @@ extension SwiftUIWrapperView: CalendarItemViewRepresentable { | |
|
||
} | ||
|
||
public struct ContentAndID: Equatable, SwiftUIWrapperViewContentIDUpdatable { | ||
public struct ContentAndID: Equatable { | ||
|
||
// MARK: Lifecycle | ||
|
||
public init(content: Content, id: AnyHashable) { | ||
// TODO: Remove `id` and rename this type in the next major release. | ||
public init(content: Content, id _: AnyHashable) { | ||
self.content = content | ||
self.id = id | ||
} | ||
|
||
// MARK: Public | ||
|
@@ -182,10 +166,6 @@ extension SwiftUIWrapperView: CalendarItemViewRepresentable { | |
false | ||
} | ||
|
||
// MARK: Internal | ||
|
||
var id: AnyHashable | ||
|
||
// MARK: Fileprivate | ||
|
||
fileprivate let content: Content | ||
|
@@ -207,67 +187,3 @@ extension SwiftUIWrapperView: CalendarItemViewRepresentable { | |
} | ||
|
||
} | ||
|
||
// MARK: - SwiftUIWrapperViewContentIDUpdatable | ||
|
||
protocol SwiftUIWrapperViewContentIDUpdatable { | ||
var id: AnyHashable { get set } | ||
} | ||
|
||
// MARK: UIResponder Next View Controller Helper | ||
|
||
extension UIResponder { | ||
/// Recursively traverses up the responder chain to find the closest view controller. | ||
fileprivate func closestViewController() -> UIViewController? { | ||
self as? UIViewController ?? next?.closestViewController() | ||
} | ||
} | ||
|
||
// MARK: - IDWrapperView | ||
|
||
/// A wrapper view that uses the `id(_:)` modifier on the wrapped view so that each one has its own identity, even if it was reused. | ||
@available(iOS 13.0, *) | ||
private struct IDWrapperView<Content: View>: View { | ||
|
||
let content: Content | ||
let id: AnyHashable | ||
|
||
var body: some View { | ||
content | ||
.id(id) | ||
} | ||
|
||
} | ||
|
||
// MARK: - HostingController | ||
|
||
/// The `UIHostingController` type used by `SwiftUIWrapperView` to embed SwiftUI views in a UIKit view hierarchy. This | ||
/// exists to disable safe area insets and set the background color to clear. | ||
@available(iOS 13.0, *) | ||
private final class HostingController<Content: View>: UIHostingController<Content> { | ||
|
||
// MARK: Lifecycle | ||
|
||
override init(rootView: Content) { | ||
super.init(rootView: rootView) | ||
|
||
// This prevents the safe area from affecting layout. | ||
_disableSafeArea = true | ||
} | ||
|
||
@MainActor | ||
required dynamic init?(coder _: NSCoder) { | ||
fatalError("init(coder:) has not been implemented") | ||
} | ||
|
||
// MARK: Internal | ||
|
||
override func viewDidLoad() { | ||
super.viewDidLoad() | ||
|
||
// Override the default `.systemBackground` color since `CalendarView` subviews should be | ||
// clear. | ||
view.backgroundColor = .clear | ||
} | ||
|
||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
not ideal, but way faster than the previous strategy of giving every view an ID
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We could also add an API in the future to opt-out of this behavior if someone doesn't need
onAppear
oronDisappear
callbacks in their views, which would get them back ~20% CPU usage when scrolling fast 🤯