我想通過使用我的ThirdClass : NSObject
類中聲明的方法以編程方式向我的ViewController : UIViewController
添加子視圖。這裏是我的代碼:使用實例方法以編程方式添加子視圖
在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發佈,
您正在調用[instanceOfThirdClass createView];但方法名稱是createApp。直接得到你的例子,然後我們可以繼續。你也沒有說過什麼不起作用。它是否抱怨你的方法名稱是錯誤的(他們是)。它靜靜地失敗了嗎?它沒有找到方法嗎? – 2015-02-10 11:06:39
'createView'與'createApp'? – orkenstein 2015-02-10 11:06:57
除了調用錯誤的方法之外,您並未將子視圖添加到目標對象的視圖中。而不是在_ThirdClass.m_中創建_ViewController_的對象,然後向其添加子視圖,將_myView_返回給接收器,然後添加子視圖。 – Gandalf 2015-02-10 11:10:04