Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set parentViewController in UIViewController?

The parentViewController property of UIViewController is readonly, but I am nesting custom view controllers and would like to use this property.

However, since it is readonly, and I found no other way to set this property, my quesion is: how do I set it?

Obviously, UINavigationController can set the property somehow in -pushViewController, and so can -presentModalViewController, so it must be possible.

I am aware that I can just add my own UIViewController property, but I'm sure that parentViewController is, in principle, the correct property.

like image 602
mrueg Avatar asked Sep 07 '09 21:09

mrueg


People also ask

What is the difference between UIView and UIViewController?

They are separate classes: UIView is a class that represents the screen of the device of everything that is visible to the viewer, while UIViewController is a class that controls an instance of UIView, and handles all of the logic and code behind that view.

What is a UIViewController subclass?

The UIViewController class defines the shared behavior that's common to all view controllers. You rarely create instances of the UIViewController class directly. Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller's view hierarchy.

How do I get Viewcontroller from view?

If you need to find the view controller that is responsible for a particular view, the easiest thing to do is walk the responder chain. This chain is built into all iOS apps, and lets you walk from one view up to its parent view, its grandparent view, and so on, until it reaches a view controller.


2 Answers

Solution is:

   - (void)setParentController:(UIViewController*)parent{
 [self setValue:parent forKey:@"_parentViewController"];
    }

It does not cause problems with linker!

PS: Don't use "setParentViewController" as method name, because this method exists in private API and Apple say: "The non-public API that is included in your application is setParentViewController:.

If you have defined a method in your source code with the same name as the above mentioned API, we suggest altering your method name so that it no longer collides with Apple's private API to avoid your application being flagged with future submissions.

Please resolve this issue in your next update..."

like image 188
abuharsky Avatar answered Oct 05 '22 11:10

abuharsky


I realize this question was asked before iOS 5, but for the reference, you should use addChildViewController when you want to nest UIViewControllers. This will also automatically set the parentViewController property.

- (void)addChildViewController:(UIViewController *)childController NS_AVAILABLE_IOS(5_0);

You can read more about "Creating Custom Content View Controllers" at Apple.

like image 27
Kobski Avatar answered Oct 05 '22 12:10

Kobski