Change the parent of a view

1.6k views Asked by At

I have a table view that i would display at some point after I get some results from the database

@IBOutlet weak var resultSetView: UITableView!

I this table view is already made in the ViewController

I would like to put this element in another view like a dock view maybe programmatically. Depending on my requirement. In a different case, maybe I would like to place it in another location.

How do I do that?

2

There are 2 answers

4
Antonio Lipiz On BEST ANSWER

class ViewController: UIViewController {

 @IBOutlet weak var resultSetView: UITableView!
 @IBOutlet weak var nestedDockView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()


    nestedDockView.addSubview(resultSetView);


}
2
Kenny Lim On

Assuming your tableView is retained. You can easily do this:

[tableView removeFromSuperview];

[dockView addSubview:tableView];

When doing this, beware:

When you reparent the view, it will inherit new layout constraint from the new parent which can be different from original view.

If you are thinking to reparent this across VC, it should work but it's really messy in terms of s/w design and encapsulation.