从appdelegate调用方法时无法添加子视图

时间:2015-08-31 09:43:06

标签: ios objective-c

我在appdelegate中调用此方法

[[[ViewController alloc] init] performSelectorOnMainThread:@selector(callMethod) withObject:nil waitUntilDone:NO];
ViewController.h中的

方法

@interface ViewController : UIViewController
-(void)callMethod;
@end
ViewController.m中的

方法

-(void)callMethod{
    NSLog(@"Method was call.....");
    UIView *myView = [[UIView alloc] initWithFrame:self.view.bounds];
    myView.backgroundColor = [UIColor colorWithRed:0.113725F green:0.615686F blue:0.411765F alpha:1.0F];
    [self.view addSubview:myView];

}

它可以在控制台中打印但addSubView不起作用。 如何使addSubView工作。 谢谢。 :)

1 个答案:

答案 0 :(得分:1)

您需要在堆栈上首先push这个新分配的视图控制器[[ViewController alloc] init],以便查看它。或者,如果此控制器已经推送标签您不必使用alloc关键字重新分配

appdelegate 中尝试这样:

// Get the visible viewController
ViewController *vc = [self.navigationController visibleViewController];
[vc performSelectorOnMainThread:@selector(callMethod) withObject:nil waitUntilDone:NO];
相关问题