ra1028/Carbon

How to create Content as UIViewController

dangthaison91 opened this issue · 1 comments

Checklist

Expected Behavior

I have some UIViewControlers will be embedded in UITableViewCell. This require calling addChildController and didMove(toParent:) when deque cell.

At the moment, seem that Carbon does not support to do that.

Hi @dangthaison91

Carbon supports UIViewController as content of components, but doesn't support life cycle synchronization by calling addChildController.
This is because each application has different specifications, such as whether to call removeFromParent when the cell goes out of the visible area.
There are also cases where you don't need to call addChildController. When the cell first enters the visible area, the life cycle such as viewWillAppear is called only once.
In conclusion, you should create a class inherited from UITableViewAdapter and customize it, and call addChildController arbitrary timing.

for example:

final class UITableViewCustomAdapter: UITableViewAdapter {
    weak var parentViewController: UIViewController?

    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        super.tableView(tableView, willDisplay: cell, forRowAt: indexPath)

        if let cell = cell as? UITableViewComponentCell, let content = cell.renderedContent as? UIViewController {
            parentViewController?.addChild(content)
            content.didMove(toParent: parentViewController)
        }
    }

    override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        super.tableView(tableView, didEndDisplaying: cell, forRowAt: indexPath)

        if let cell = cell as? UITableViewComponentCell, let content = cell.renderedContent as? UIViewController {
            content.willMove(toParent: nil)
            content.removeFromParent()
        }
    }
}