2

Is it possible to embed (add as subview) a UITableViewController into another View Controller programmatically? I found a few answers here on StackOverflow but none worked for me with ARC and iOS6 SDK.

I know you can do this easily with Navigation and TabBar controllers but I am more curious about adding tableviews to a regular View controller. I need my tableview to occupy the lower part of the available screen space (I need the rest for other purposes, for which neither tab nor navigation types are suitable).

When I tried to do it, however, it did not work. I instantiated a subclassed UITableViewController, but when I added it to my self.view as a subview, the compiler said I tried to use "incompatible pointer types." Not only that, my instantiated UITableViewController does not have a .frame property, so I cannot set it dimensions, which would be the whole point of this exercise.

4

2 回答 2

4

Building upon ogres answer, you should add the tableViewController's view as a subview, but it is not everything. The tableViewController is a viewController and it needs to know its parent and its children, to do its viewController-job correctly. I do not know any details here, but there is an entire talk about this from WWDC 2011 called "Implementing UIViewController Containment".

One problem I have experienced when only adding the view as a subview is that target actions don't seem to work. Tapping a UIButton or similar causes either a EXC_BAD_ACCESS or a unrecognized selector sent to instance.

So I recommend that you do something like this:

UIViewController *vc = //Your tableViewController
[self addChildViewController:vc]; //Important
[self.view addSubview:vc.view];

//If you want to set the frame, set the frame of the tableViewController's view
vc.view.frame = ...
于 2012-12-25T18:29:49.143 回答
1

yes , you can use tableview in another view without any problems

UITableViewController, but when I added it to my self.view as a subview

are you trying to add viewcontroller as subview or its view ? ( viewcontroller.view )

UITableViewController does not have a .frame property,

of course it does not have .frame property , it is a view CONTROLLER , you should see .view.frame

于 2012-12-25T18:05:31.857 回答