[英]Add subview programmatically using instance method
我試圖通過使用在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發布的視圖,
您將創建的視圖附加到新的實例化視圖控制器,但是顯示的視圖是屬於該視圖的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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.