Customize UIViewController transition trong iOS với UIStoryboardSegue
This post has been more than 2 years since it was last updated.
Introduction
Nếu bạn đã từng customize transition một view controller bằng cách implement UIViewControllerTransitioningDelegate và UIViewControllerContextTransitioning trong view controller đó, bạn có thể thấy những nhược điểm của cách làm này.
Đó là code trong view controller sẽ dài, phức tạp hơn mà lại không thể tái sử dụng một cách linh hoạt.
Trong bài viết này, chúng ta sẽ tìm hiểu cách customize transition view controller độc lập, tái sử dụng linh hoạt bằng cách subclass UIStoryboardSegue.
Với cách này, chúng ta có thể sử dụng trong Interface Builder thông qua custom segue type. Không những vậy, custom segue còn có thể dùng được trong cả những project thuần code UI, không dùng storyboard.
Create a custom segue
Tạo project mới, tạo class mới BottomCardSegue, kế thừa class UIStoryboardSegue.
Và override lại func perform()
mặc định của segue rồi present destination viewcontroller.
class BottomCardSegue: UIStoryboardSegue {
override func perform() {
source.present(destination, animated: true, completion: nil)
}
}
Chỉ với đoạn code trên, custom segue BottomCardSegue đã có thể sử dụng được rồi nhưng nó vẫn chưa thể hiển được sự khác biệt nào so với segue mặc định cả.
Code phần tableView.
class ListViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.tableFooterView = UIView()
}
}
extension ListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Item \(indexPath.row + 1)"
cell.selectionStyle = .none
return cell
}
}
extension ListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "goToDetail", sender: self)
}
}
Set up the storyboard
Trong project vừa tạo, ở Main.storyboard, tạo các view controller như trong hình trên.
Ở init view controller, thêm 2 button Show và Show Programatically.
Các view controller còn lại đơn giản là một UINavigationController với rootViewController chứa một table view đơn giản.
- Giữ phím Control và kéo thả từ button Show sang navigation controller.
- Chọn bottom card từ list segue type.
Interface Builder sẽ tự động thêm một segue type có tên là bottom card từ custom segue BottomCardSegue bằng cách lower case từ tên class.
Prepare for segue
Tiếp theo, chúng ta thêm một nút Done vào root view controller.
class ViewController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let navigationController = segue.destination as? UINavigationController else {
return
}
let rootViewController = navigationController.viewControllers.first
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(hide))
rootViewController?.navigationItem.rightBarButtonItem = doneButton
}
@objc private func hide() {
dismiss(animated: true, completion: nil)
}
}
Customize transition
Trong function perform()
của class BottomCardSegue, set transitioningDelegate
của destination view controller bằng self
để control transition.
destination.transitioningDelegate = self
UIKit không tự động set retain cho các instance của class UIStoryboardSegue. Vì vậy chúng ta phải kiểm soát và giải phóng một cách thủ công self
reference.
Tạo strong self
reference khi bắt đầu transition và set nó bằng nil
khi dismiss để tránh leak memory.
class BottomCardSegue: UIStoryboardSegue {
private var selfRetainer: BottomCardSegue? = nil
override func perform() {
...
selfRetainer = self
...
}
}
Cuối cùng, set modal presentation style bằng .overCurrentContext
để cho phép presenting view controller hiển thị dưới nền view controller được present.
destination.modalPresentationStyle = .overCurrentContext
Code hoàn chỉnh:
class BottomCardSegue: UIStoryboardSegue {
private var selfRetainer: BottomCardSegue? = nil
override func perform() {
destination.transitioningDelegate = self
selfRetainer = self
destination.modalPresentationStyle = .overCurrentContext
source.present(destination, animated: true, completion: nil)
}
}
Bước tiếp theo, chúng ta cần implement các function của UIViewControllerTransitioningDelegate trong extension của BottomCardSegue.
Đó là 2 function:
animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
Cả 2 function này đều cần trả về instance của class UIViewControllerAnimatedTransitioning tương ứng khi present và khi dismiss.
Tiếp theo tạo class tên Presenter, subclass của UIViewControllerAnimatedTransitioning rồi implement 2 function:
transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval
: thời gian animate của transition.animateTransition(using transitionContext: UIViewControllerContextTransitioning)
: thực hiện các setup, animate trong function này.
private class Presenter: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let toView = transitionContext.view(forKey: .to),
let toViewController = transitionContext.viewController(forKey: .to) else {
return
}
// Set constraint cho presenting view
toView.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(toView)
let bottom = max(20 - toView.safeAreaInsets.bottom, 0)
container.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: toView.bottomAnchor, constant: bottom).isActive = true
container.safeAreaLayoutGuide.leadingAnchor.constraint(equalTo: toView.leadingAnchor, constant: -20).isActive = true
container.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: toView.trailingAnchor, constant: 20).isActive = true
if toViewController.preferredContentSize.height > 0 {
toView.heightAnchor.constraint(equalToConstant: toViewController.preferredContentSize.height).isActive = true
}
// Styling presenting view
toView.layer.masksToBounds = true
toView.layer.cornerRadius = 20
// Thực hiện các animation của transition
container.layoutIfNeeded()
let originalOriginY = toView.frame.origin.y
toView.frame.origin.y += container.frame.height - toView.frame.minY
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
toView.frame.origin.y = originalOriginY
}) { (completed) in
transitionContext.completeTransition(completed)
}
}
}
Và class Dismisser tương tự cho quá trình dismiss.
private class Dismisser: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.2
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let fromView = transitionContext.view(forKey: .from) else {
return
}
UIView.animate(withDuration: 0.2, animations: {
fromView.frame.origin.y += container.frame.height - fromView.frame.minY
}) { (completed) in
transitionContext.completeTransition(completed)
}
}
}
Cuối cùng set preferredContentSize
của UINavigationController bằng kích thước tuỳ ý.
Trong 2 function của UIViewControllerTransitioningDelegate, return instance của class Presenter và Dismisser tương ứng.
extension BottomCardSegue: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return Presenter()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return Dismisser()
}
}
Programmatically Transition
Như vậy chúng ta đã hoàn thành việc customize segue và transition. Khi nhấn nút Show, Interface Builder sẽ tự động sử dụng BottomCardSegue vừa tạo.
Tuy nhiên, chúng ta cũng có thể perform segue bằng code.
Tạo @IBAction
cho button Show Programatically như sau:
@IBAction private func showProgrammaticallyButtonTapped(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// Init view controller cần present
let navigationController = storyboard.instantiateViewController(withIdentifier: "NavigationController")
// Tạo custom instance của BottomCardSegue và set destination view controller
let segue = BottomCardSegue(identifier: nil, source: self, destination: navigationController)
// Gọi function prepare segue nếu cần
prepare(for: segue, sender: nil)
// Perform segue
segue.perform()
}
Kết quả:
Link source demo: https://github.com/oNguyenXuanThanh/StudyReport122018
All Rights Reserved