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

Alamofire vs URLSession

Alamofire vs URLSession: a comparison for networking in Swift Alamofire and URLSession both help you to make network requests in Swift. The URLSession API is part of the foundation framework, whereas Alamofire needs to be added as an external dependency. Many  developers  doubt  whether it’s needed to include an extra dependency on something basic like networking in Swift. In the end, it’s perfectly doable to implement a networking layer with the great URLSession API’s which are available nowadays. This blog post is here to compare both frameworks and to find out when to add Alamofire as an external dependency. Build better iOS apps faster Looking for a great mobile CI/CD solution that has tons of iOS-specific tools, smooth code signing, and even real device testing? Learn more about Bitrise’s iOS specific solutions! This shows the real power of Alamofire as the framework makes a lot of things easier. What is Alamofire? Where URLSession...

Swift Tool Belt, Part 1: Adding a Border, Corner Radius, and Shadow to a UIView with Interface Builder

During my iOS work, I’ve assembled a set of code that I bring with me on every iOS project. I’m not talking about large frameworks or CocoaPods here. These are smaller Swift extensions or control overrides that are applicable to many projects. I think of them as my tool belt. In this post, I’ll show you an extension that will add a border, a corner radius, and a shadow to any UIView, UIButton, or UILabel and allow you to preview what it will look like in Interface Builder. Back in 2014, I wrote a blog post on Expanding User-Defined Runtime Attributes in Xcode where I added a border, corner radius, and shadow to a UIView using Interface Builder’s user-defined runtime attributes. This solution had no type checking—you had to type the property you wanted to modify by hand and often had to look up what it was called. You also had to run your project in order to see the effect of the runtime attribute. Starting with Xcode 6 , there is a new mech...

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...