Skip to main content

Customize UIViewController transition trong iOS với UIStoryboardSegue


Introduction

Nếu bạn đã từng customize transition một view controller bằng cách implement UIViewControllerTransitioningDelegateUIViewControllerContextTransitioning 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 ShowShow 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 PresenterDismisser 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ả:
Reference: https://www.swiftkickmobile.com/elegant-custom-uiviewcontroller-transitioning-uiviewcontrollertransitioningdelegate-uiviewcontrolleranimatedtransitioning/
Link source demo: https://github.com/oNguyenXuanThanh/StudyReport122018

Comments

Popular posts from this blog

Swift GCD part 1: Thread safe singletons

Preview Singletons are entities, referenced to the same instance of a class from everywhere in your code. It doesn't matter if you like them or not, you will definitely meet them, so it's better to understand how they work. Constructing and handling a set of data doesn't seem to be a big challenge at first glance. The problems appear when you try to optimise the user experience with background work and your app starts acting weird. ??‍♂️ After decades of watching your display mostly with a blank face, you finally realize that your data isn't handled consistently by the manager because you're accessing it (running tasks on it) from multiple threads at the same time. So you really do have to deal with making your singletons thread safe. This article series is dedicated to thread handling using Swift. In the first part below you will get a comprehensive insight into som...

Thread safe singleton’s in Swift

What are singletons? — Singleton is design patterns which says that there should be only one instance of the class for the lifetime of the application. One the best example of Singleton is AppDelegate . How to write a singleton class ? class DefaultDict{ private var dict:[String:Any] = [:] public static let sharedManager = DefaultDict() private init(){ } public func set(value:Any,key:String){ dict[key] = value } public func object(key:String) -> Any?{ dict[key] } public func reset(){ dict.removeAll() } }   Testing singleton class under concurrent circumstances. We are going to write an example where we will set values in dict from various threads and even try to access some with different threads. When we do this we will encounter a crash. If you look closely it will be because of race condition and the crash will be on line set(value:Any,key:String) . class ViewController: UIViewController { ...

Frame vs Bounds in iOS

This article is a repost of an answer I wrote on Stack Overflow . Short description frame = a view’s location and size using the parent view’s coordinate system ( important for placing the view in the parent) bounds = a view’s location and size using its own coordinate system (important for placing the view’s content or subviews within itself) Details To help me remember frame , I think of a picture frame on a wall . The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame’s x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y. To help me remember bound...