简洁优雅的 Dropdown Transition
为什么?
我需要在我的应用程序中执行下拉转换,我发现了很多提供所需功能的大库。但它们都有一个问题:它们并未实现为自定义转换,而是作为某种视图动画。
此库通过提供使用 UIPresentationController
和 UITransitionCoordinator
实现的自定义模态转换来解决此问题。它提供更大的灵活性,更适合一些遵循标准架构和导航模式的项目(例如 Router
、Navigator
和 Coordinator
模式)使用
演示
安装
安装 DropdownTransition 有多种选项
使用 Carthage 依赖管理器,将以下行添加到 Cartfile
github "nugmanoff/DropdownTransition" ~> 1.0.0
使用 CocoaPods,将以下行添加到您的 Podfile
pod 'DropdownTransition', '~> 1.0.0'
使用 Swift Package Manager,将以下行添加到您的 Package.swift
dependencies: [
.package(url: "https://github.com/nugmanoff/DropdownTransition.git", .exact("1.0.0")),
]
或者只需直接将 DropdownTransition
文件夹中的 *.swift
文件拖到您的项目中(我最喜欢的选项)。
使用说明
- 您需要将要显示的
UIViewController
子类符合DropdownPresentable
协议。
class SomeViewController: UIViewController, DropdownPresentable {
// ...
}
- 您需要将
DropdownTransitioningDelegate
实例变量存储在一个可供调用present
方法访问的地方(例如在Router
实现中的Coordinator
模式)。
let dropdownTransitioningDelegate = DropdownTransitioningDelegate()`
- 作为最终步骤,您需要通过调整将要显示的视图控制器选项,并调用带有它的
present
函数来执行实际过渡。
let someViewController = SomeViewController()
someViewController.transitioningDelegate = dropdownTransitioningDelegate
someViewController.modalPresentationStyle = .custom
navigationController?.present(someViewController, animated: true, completion: nil)
如果您正在使用 Auto Layout 并且想知道如何以正确的高度显示控制器,请参阅 专家提示
高级使用
为了定制各种显示参数,您需要覆盖实现来自 DropdownPresentable
协议中需要的变量,否则它们的值将被设置为一些合理的默认值。
var isDraggingEnabled: Bool { get } // option that indicates whether you can drag (pan gesture) the dropdown controller or not
var dismissAfterRelease: Bool { get } // when enabled automatically dismisses controller when it surpasses threshold value
var dismissDraggingTranslationThreshold: CGFloat { get } // threshold value for dismissals
var stretchableBackgroundColor: UIColor { get } // background color of the view that stretches at the top of the controller (if dragging is enabled)
var dismissAfterTappingDimmingView: Bool { get } // when enabled automatically dismisses controller upon tap on the dimmed (black) area
var isFeedbackEnabled: Bool { get } // whether or not haptic feedback is generated on reaching threshold value
var feedbackStyle: UIImpactFeedbackGenerator.FeedbackStyle { get } // haptic feedback style
专家提示
要获得所需的高度和过渡行为,必须正确设置呈现的 UIViewController
的内联高度。幸运的是,您可以在 UIViewController
的 viewDidLayoutSubviews
和 viewDidLoad
方法中调用此函数来轻松完成。
private func updatePreferredContentSize() {
view.updateConstraintsIfNeeded()
let viewSize = CGSize(width: UIScreen.main.bounds.width, height: .leastNonzeroMagnitude)
preferredContentSize = view.systemLayoutSizeFitting(viewSize,
withHorizontalFittingPriority: .required,
verticalFittingPriority: .defaultLow)
如果您仍然遇到控制器高度设置不正确的问题,请确保您获得了正确的约束,并且它们是可以满足的。
如果您想了解更多的细节,我已将一个演示 示例 添加到了库中。
支持
如果您对库有任何问题,发现了错误或想要做出贡献,请在国际 GitHub 上发起一个 问题。
本项目的作者是 @nugmanoff
本项目遵循MIT许可证