如何在ViewController类范围之外执行?

如何在ViewController类范围之外执行[self.view addSubview:lbl]?

要么:

如何在ViewController类之外的主视图中将标签或其他视图添加到其他类中?

谢谢

- (void)viewDidLoad { [super viewDidLoad]; UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; [lbl setText:@"hi there"]; [self.view addSubview:lbl];// <-- this works, but ... // what is "self" referring to? // and how can I declare and call from another class? ... UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; [lbl setText:@"hi there"]; calcRomanAppDelegate *v = [[calcRomanAppDelegate new] init]; [v.viewController.view addSubview:lbl]; // this compiles, but... // fails to shows a label on the form ... UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; [lbl setText:@"hi there"]; calcRomanViewController *v = [[calcRomanViewController new] init]; [v.view addSubview:lbl]; // this just makes a call back to viewDidLoad... endless loop } 

好吧, view只是UIViewController类的一个属性。 假设你在某处有你的UIViewController *controller变量,你可以使用

 [controller.view addSubview:subview] 

之所以[v.viewController.view addSubview:lbl]; 不起作用的是vcalcRomanAppDelegate实例。 每个应用程序都有一个app delegate的共享实例 ,可以通过[[NSApplication sharedApplication] delegate] 。 因此,您的代码将变为:

 calcRomanAppDelegate *v = (calcRomanAppDelegate *)[[NSApplication sharedApplication] delegate]; [v.viewController.view addSubview:lbl]; // this compiles but shows a blank form 

另外在你编写的代码中,我将指出new方法返回一个初始化对象,因此你不需要在[[calcRomanAppDelegate new] init]额外调用[[calcRomanAppDelegate new] init] 。 我建议不使用new方法,而是使用alloc ,它不会调用初始化程序。 显然,这不是特定情况下的问题,但重要的是要知道。

不确定你想要完成什么。

但是,假设您在view1中,并希望创建另一个视图(view2),并将UILabel lbl添加到此view2中。 这是你要做的:

 UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(x, y, w, h)]; //x,y, wh are for your view2 [view addSubview:lbl]; [self.view addSubview:view2]; //self is your current viewcontroller - you add view2 on top of view1 

另一方面,如果您已经有ViewController类ViewController2.h,则定义ViewController2.m和ViewController2.xib。 这是你要做的:

 ViewController2 *viewController2 = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil]; [viewController2.view addSubview:lbl]; [self.view addSubview:viewController2.view]; //same as before, you need to add viewController2's view to the current view 

希望这有帮助。