开发者

Access UIView with Class Method?

I have 2 view controllers AViewController and BViewController as an example. I want to add a UI element in the second BViewController from the first AViewController. I thought I would make this happen through the class method but the UIView is not accessable in the BViewController's class method when called from AViewController.

Implementation of BViewController +(void)addThatButton{ UIButton *btn = ...... [self.view addSubview:btn]; //<== ERROR //[BViewController.view addSubview:btn]; //<== ALSO ERROR }

Implemention of AViewController [BViewController addThatButton];

Error message I get is "request for member 'view' in something not a structure or union". How to implememnt what I need in the right way or, in other words, how to access BViewController view from the A class?

开发者_StackOverflow中文版

Thanks


You need to create a function in BViewController

In BViewController.h

UIButton *btnB;

-(void)passButtonFromA:(UIButton *)btn;

In BViewController.m

-(void)passButtonFromA:(UIButton *)btn{
     btnB = btn;
}

-(void)viewWillAppear:(BOOL)animated{

    [self.view addSubView:btnB];
}

In AViewController.m

 BViewController *bViewController =[[BViewController alloc]initWithNibName:.. ...]; //allocated bViewController using your nib file
 [bViewController passButtonFromA:btnA];
 [self.navigationViewController pushViewController:bViewController animated:YES];


Simple answer: A "+" method is a static method, and "self" refers not to an instance but rather to the class. Thus self.view is meaningless.

Your basic scheme would work (with a few caveats) if you changed to a "-" method and somehow got the address of your BViewController instance in the AViewController and used that address in the call.


I thought I would make this happen through the class method but the UIView is not accessable in the BViewController's class method when called from AViewController.

That's because there is no UIView to access. A class method runs independently of any instance. If you want a particular object to be updated, then you need to call one of its instance methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜