MySecondViewController не будет отображаться правильно - PullRequest
0 голосов
/ 25 июня 2011

Я программно создал второй контроллер вида (MySecondViewController), который был полностью готов и подключен без использования редактора визуальных объектов.

Моя проблема в том, что когда я запускаю приложение, появляется только оригинальный контроллер представления (HelloWorldViewController); Контроллер второго вида не отображается. Когда я нажимаю на представление для HelloWorldViewController, ничего не появляется.

Можете ли вы сказать мне, что не так?

windowBasedAppAppDelegate.h

#import <UIKit/UIKit.h>

//-- Add a forward reference to the HelloWorldViewController class --

@class HelloWorldViewController;

@interface windowBasedAppAppDelegate : NSObject <UIApplicationDelegate> {
    //-- create an instance of the view controller--
    HelloWorldViewController *viewController;

}

@property (nonatomic, retain) IBOutlet UIWindow *window;

//--Expose the view controller as a property--
@property (nonatomic, retain) IBOutlet HelloWorldViewController *viewController;

@end

windowBasedAppAppDelegate.m

#import "windowBasedAppAppDelegate.h"
#import "HelloWorldViewController.h"
#import "MySecondViewController.h"

@implementation windowBasedAppAppDelegate


@synthesize window;
@synthesize viewController;

//-- a second view controller object--
MySecondViewController *mySecondViewController;

- (BOOL)application:(UIApplication *)application     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    //-- add the new view to the current window--
    //-- instantiate the second view controller --
    mySecondViewController = [[MySecondViewController alloc]
                          initWithNibName:nil
                          bundle:nil];

   // -- add the view from the second controller --
   //[window addSubview:mySecondViewController.view];

   [window addSubview:viewController.view];
   [self.window makeKeyAndVisible];
   return YES;
}

- (void)dealloc
{
    [MySecondViewController release];
    [viewController release];
    [window release];
    [super dealloc];
}

@end

MySecondViewController.h

#import <UIKit/UIKit.h>


@interface MySecondViewController : UIViewController {
    //-- create two outlets, label and button --
    UILabel *label;
    UIButton *button;

}

//-- expose the outlets as properties --

@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UIButton *button;

// -- declaring the IBAction ---
- (IBAction) buttonClicked: (id)sender;

@end

MySecondViewController.h

#import "MySecondViewController.h"


@implementation MySecondViewController

@synthesize label, button;

- (IBAction) buttonClicked: (id)sender {
    UIAlertView *alert =
    [[UIAlertView alloc] initWithTitle:@"Action Invoked!" message:@"Button clicked"     delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

HelloWorldViewController.h

#import <UIKit/UIKit.h>


@interface HelloWorldViewController : UIViewController {

}

@end

HelloWorldViewController.m

импорт "HelloWorldViewController.h"

@implementation HelloWorldViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
    }
    return self;
    }

- (void)dealloc
{
    [super dealloc];
}

Добавлен код из MySecondViewController.m

//-- add the views to the view window --
    [self.view addSubview:label];
    [self.view addSubview:button];
    [view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
    self.view = view;
    [super viewDidLoad];

Ответы [ 2 ]

1 голос
/ 25 июня 2011

Поскольку view инициализируется и имеет правильный фрейм, проблема может заключаться в такой последовательности кода,

[window addSubview:mySecondViewController.view];
[window addSubview:viewController.view];

Поскольку viewController view будет иметь тот же кадр, он будет добавлен к mySecondViewController * view. Так что вам придется удалить вторую строку, чтобы отобразился вид.

0 голосов
/ 25 июня 2011

На самом деле вы никогда не выдвигаете новый контроллер вида на экран.

 mySecondViewController = [[MySecondViewController alloc]
                      initWithNibName:nil
                      bundle:nil];

// -- add the view from the second controller --
//[window addSubview:mySecondViewController.view];

   [window addSubview:viewController.view];

Вы добавляете viewController.view (который должен быть неопределенным ...), но не mySecondViewController.view.

Кроме того, programHasFinishedLaunching может быть не самым лучшим местом, чтобы подтолкнуть его. Если бы я был тобой, я бы поставил на первой странице кнопку, которая открывает новый вид, так проще.

...