繁体   English   中英

self.view insertSubView … 不应该是 self.view,但是什么?

[英]self.view insertSubView … not supposed to be self.view, but what?

我有一个 UIViewController 显示不同的 UIViewController 子类。 在主 UIViewController.m 中,我在应用启动时有一个名为“Home”的子类。

现在,加载了主页视图,我有一个按钮,我想用它来切换到另一个名为“PreGameInfo”的视图。 我正在尝试使用下面的代码:

- (IBAction)showPreGameInfo:(id)sender {
    [self.view insertSubview:preGameInfo.view atIndex:0];
}

它不起作用,我知道这是因为“self.view”需要引用主 UIViewController 而不是“Home”视图的 self。 有谁知道在 SubView 中使用 UIButton 时如何将 SubView 插入主 UIViewController ???

谢谢!

你可以使用一个代理。 这很容易

所以在你的信息视图 controller 中实现这个;

在 InformationViewController.h

@protocol InformationViewControllerDelegate;

@interface InformationViewController : UIViewController {
    id <InformationViewControllerDelegate> delegate;
}

@property (nonatomic, assign) id <InformationViewControllerDelegate> delegate;

- (IBAction)returnBack:(id)sender;

@end

@protocol InformationViewControllerDelegate

- (void)InformationViewControllerDidFinish:(InformationViewController *)controller;

@end

在 InformationViewController.m 中

- (IBAction)returnBack:(id)sender {
    [self.delegate InformationViewControllerDidFinish:self];
}

并在任何视图 controller 中使用委托,您需要这样:

在 HomeViewController.h

#import "InformationViewController.h"
@interface HomeViewController : UIViewController <InformationViewControllerDelegate> {

}

编写将视图从主页视图更改为信息视图的方法

- (IBAction)goToInformationView:(id)sender;

在 HomeViewController.m

- (IBAction)goToInformationView:(id)sender {
    InformationViewController *controller = [[InformationViewController alloc] initWithNibName:nil bundle:nil];
    controller.delegate = self;
// You can chose the transition you want here (they are 4 see UIModalTransitionStyle)
        controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        [self presentModalViewController:controller animated:YES];
        [controller release];
    }

最后但并非最不重要的委托方法,它在 InformationViewController 完成时通知 HomeViewController

- (void)InformationViewControllerDidFinish:(InformationViewController *)controller {
    [self dismissModalViewControllerAnimated:YES];
}

我希望它有帮助

- (IBAction)showPreGameInfo:(id)sender {
    [superview insertSubview:preGameInfo.view atIndex:0];
}

这段代码有效吗?

[self.parentViewController.view addSubview:myView];

只需在 modalView 中执行此操作:

[self presentModalViewController:preGameInfo animated:YES]

或者你可以做这样的事情......

此行会将您的新视图添加到 windows rootViewControllers 视图

[self.view.window.rootViewController.view addSubview:preGameInfo.view];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM