我正在尝试使用我ViewController : UIViewController
类中声明的方法以编程方式将子视图添加到ThirdClass : NSObject
。这是我的代码:
在ViewController.m文件中,我执行:
- (void)viewDidLoad {
[super viewDidLoad];
ThirdClass *instanceOfThirdClass = [[ThirdClass alloc] init];
[instanceOfThirdClass createView];
}
在我的ThirdClass.m中,我声明了实例方法:
-(void)createView{
NSLog(@"enter create app");
UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(50, 0, 320, 100)];
[myView setBackgroundColor:[UIColor redColor]];
ViewController *instanceOfViewController = [[ViewController alloc]init];
[instanceOfViewController.view addSubview:myView];
}
所以问题显然是我试图将创建的视图添加到类实例中,正确的方法是在@gary-riches下面发布的那个,
答案 0 :(得分:4)
您正在将创建的视图附加到新的实例化视图控制器,但您显示的视图是属于ViewController.m的视图。您需要将视图添加到ViewController.m的视图中。
更新您的createView方法以处理视图:
-(void)createViewInView:(UIView *)aView{
NSLog(@"enter create app");
UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(50, 0, 320, 100)];
[myView setBackgroundColor:[UIColor redColor]];
[aView addSubview:myView];
}
然后将您的电话改为:
[instanceOfThirdClass createViewInView:self.view];
另外,请确保在ThirdClass.h的标题中包含方法签名。它应该是:
-(void)createViewInView:(UIView *)aView;