自定义 UIViewController 添加问题

Custom UIViewController add issue

我创建了一个 UIViewController,我想将其添加到我所有视图的顶部,问题是它仅显示 1 秒,然后从屏幕上消失并取消分配。为什么会这样?

这是我的代码:

- (void)show
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.windowLevel = UIWindowLevelAlert;
    self.window.screen = [UIScreen mainScreen];
    [self.window makeKeyAndVisible];

    UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
    [mainWindow setUserInteractionEnabled:NO];
    [self.window addSubview:self.view];

    self.view.alpha = 0.0f;
    self.backgroundImage.image = [self takeSnapshot];

    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{

        self.view.transform = CGAffineTransformIdentity;
        self.view.alpha = 1.0f;

    } completion:nil];
}

- (void)dealloc
{
    NSLog(@"Screen deallocated.");
}

看着你的对象图,我假设 self 是某个视图控制器。 您的 self.view 是 Appdelegates UIWindow 的子视图。当你做

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

你的 Appdelegate window 随后被释放你的视图控制器(self)也将被释放。

所以我建议您在实际释放之前保留 UIWindow 实例。

您必须在调用 "show" 方法的地方为您的 UIViewController 保存变量。例如 - 只需创建 属性…

@属性(非原子,强)CustomViewController *cvc;

否则您的 UIViewController 实例将在该方法结束时释放。因为你的对象不会有任何强引用…

如果您使用 XIB,则可以使用此代码:您必须创建一个 UIView class,例如 HeaderView。在你的 UIViewController [我会称之为 BaseViewController].h 你必须添加一个 属性:

@property (nonatomic, strong) HeaderView *headerView;

并且在 .m 中您必须添加此代码:

- (id)init {

self = [super init];

if (self) {

    [self configureMenuView:self];
}

return self;

}

- (void)configureMenuView:(UIViewController *)vc {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"HeaderView" owner:self options:nil];
    for( id currentObject in topLevelObjects)
    {
        if([currentObject isKindOfClass:[HeaderView class]]) {
            self.headerView = (BannerView *)currentObject;
            self.headerView.frame = CGRectMake(0, 0, 768, 1024);
            self.headerView.backgroundColor = [UIColor clearColor];

            [vc.view addSubview:self.headerView];
            break;
        }
    }
     [self.bannerView.closeHeaderButton addTarget:self action:@selector(closeHeaderrView) forControlEvents:UIControlEventTouchUpInside]; // it's only an example if you want add some button in your header.

因此,在每个视图控制器中,您必须导入此 class: BaseViewContoller 并像父项一样添加它:

@interface TestViewController : HeaderViewController

希望它对你有用:)