I have a segmented control which switches between two UIViewControllers. A info view, and a list view (TableView).
I want to use the first UIViewController as the first cell of my TableView (that is on the other segment).
Is there a way to convert a UIViewController to a cell or someway to use it as a cell for a TableView?
To actually prevent selection you need to implement tableView:willSelectRowAtIndexPath: on your UITableViewDelegate and return nil for non-selectable rows.
In order to populate the tableview, you need to: In the storyboard, set your view controller to be the datasource of the tableview by dragging the "datasource" connection from the connections menu of the table view to your view controller. Make your view controller conform to the UITableViewDataSource protocol.
For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.
Use this code with your own way. Here we are adding the controllers view as subview of cell and using auto layout to manage properly. You just need to use the code by understanding.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath:indexPath)
cell.layoutIfNeeded()
let infoVC = self.storyboard.instantiateViewControllerWithIdentifier("InfoVC")
self.addChildViewController(infoVC)
cell.contentView.addSubview(infoVC.view)
infoVC.view.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addConstraint(NSLayoutConstraint(item: infoVC.view, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0))
cell.contentView.addConstraint(NSLayoutConstraint(item: infoVC.view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0))
cell.contentView.addConstraint(NSLayoutConstraint(item: infoVC.view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0))
cell.contentView.addConstraint(NSLayoutConstraint(item: infoVC.view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0))
infoVC.didMoveToParentViewController(self)
infoVC.view.layoutIfNeeded()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With