多视图应用程序编程

时间:2013-01-07 12:34:56

标签: objective-c uiviewcontroller

我想知道是否可以在不使用Interface Builder的情况下制作多视图应用。

我知道如何使用Xcode和Storyboard来实现它,但我只是希望能够以编程方式实现它。

例如:如果我的UIViewController A(默认视图)带有UIButton,而我有UIViewController B带有UIWebView,那么当我点击UIButton AI的UIViewController希望能够显示第二个视图(没有IB)。

如何将操作设置为UIButton以显示我的第二个视图(没有界面生成器)?

2 个答案:

答案 0 :(得分:1)

您可以为按钮添加目标:

[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

然后在Controller中添加此方法:

-(void)buttonPressed:(id)sender
{
    [self.superview addSubview:controllerB.view];
    [self.view removeFromSuperview];
}

答案 1 :(得分:1)

在ViewControllerA上

    - (void)viewDidLoad
    {

        UIButton  *btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn setFrame:CGRectMake(50.0f,200.0f,60.0f,30.0f)];
        [btn setTitle:@"Next" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
        [btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    -(IBAction)btnPressed:(id)sender
    {
        NextViewController *nxt=[[NextViewController alloc]initWithNibName:nil bundle:nil];
        [self.navigationController pushViewController:nxt animated:YES];
    }

在viewControllerB上

    - (void)viewDidLoad
    {
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0, 320, 460)];    
       NSURL *targetURL = [NSURL URLWithString:@"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf"];
        NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
        [webView loadRequest:request];

       [self.view addSubview:webView];
     }

确保在AppDelegate.h中应该像这样的导航控制器

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
     UINavigationController*  navController = [[UINavigationController alloc] initWithRootViewController:self.self.viewController ];
    self.window.rootViewController = navController;
    [self.window makeKeyAndVisible];
    return YES;
}