在 iOS 中,我的 View 单独工作,但无法在它们之间切换。
现在,经过大量谷歌搜索后,我喜欢基于导航的应用程序可以很好地与 View 堆栈配合使用。问题是我的所有 View 都是无 nib/xib 的,并且是在源代码中定制的。因此,我需要自己的 UINavigationController 并手动/代码推送和弹出 View 。由于每个教程要么是 nib/xib 和 IB 绑定(bind),要么只是代码片段的混搭,所以我需要一个具体的示例来说明如何做到这一点。
一个简单的例子,有2个以编程方式创建的 View (可以是空的,只需使用loadView而不是用nib/xib初始化)和一个工作堆栈( View 的推送和弹出,例如:加载应用程序,创建一些根)查看(如果需要),推送一个 View ,然后从该 View 推送第二个 View ,然后弹出它们)会很棒,或者至少以这种方式提供一个包含项目的整个源代码而不是片段的教程。
提前致谢。
编辑:经过一些额外的思考,再澄清一点也不错。我的应用程序基本上由 5 或 6 个 View 组成,这些 View 将从各自之前的 View 中调用,即向下钻取应用程序。
最佳答案
这是一个简短的代码,仅包含基本部分:
CodeViewsPushingAppDelegate.m
#import "CodeViewsPushingAppDelegate.h"
#import "ViewNumberOne.h"
@implementation CodeViewsPushingAppDelegate
@synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
UINavigationController *navController = [[UINavigationController alloc] init];
ViewNumberOne *view1 = [[ViewNumberOne alloc] init];
[navController pushViewController:view1 animated:NO];
[self.window addSubview:navController.view];
[self.window makeKeyAndVisible];
return YES;
}
ViewNumberOne.h
#import <UIKit/UIKit.h>
@interface ViewNumberOne : UIViewController
{
UIButton *button;
}
- (void)pushAnotherView;
@end
ViewNumberOne.m
#import "ViewNumberOne.h"
#import "ViewNumberTwo.h"
@implementation ViewNumberOne
- (void)loadView
{
[super loadView];
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(110, 190, 100, 20);
[button setTitle:@"Push Me!" forState:UIControlStateNormal];
[button addTarget:self action:@selector(pushAnotherView) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)pushAnotherView;
{
ViewNumberTwo *view2 = [[ViewNumberTwo alloc] init];
[self.navigationController pushViewController:view2 animated:YES];
[view2 release];
}
ViewNumberTwo.h
#import <UIKit/UIKit.h>
@interface ViewNumberTwo : UIViewController
{
UILabel *label;
}
@end
ViewNumberTwo.m
#import "ViewNumberTwo.h"
@implementation ViewNumberTwo
- (void)loadView
{
[super loadView];
label = [[UILabel alloc] init];
label.text = @"I am a label! This is view #2";
label.numberOfLines = 2;
label.textAlignment = UITextAlignmentCenter;
label.frame = CGRectMake(50, 50, 200, 200); //whatever
[self.view addSubview:label];
}
关于iphone - 以编程方式切换自定义 View (推送和弹出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7000830/