Пейзажный режим iPad - Как добавить два заставки

Я успешно закончил свое приложение после нескольких месяцев кодирования. Сейчас я пытаюсь добавить начальные изображения Splash Screen в свое приложение. Как мне поступить? У меня есть два изображения: одно - логотип компании, а другое - логотип приложения (эти заставки скрывают время загрузки). Я везде искал возможный ответ, но в итоге не нашел решения. Когда я называю одну картинку Default-Landscape.png и запускаю приложение Ipad - изображение показывается до тех пор, пока не загрузится контроллер основного вида, но я хочу, чтобы первое изображение отображалось в течение 1 секунды, а затем исчезало до второго изображения, которое будет также будет отображаться в течение 1 секунды, после чего появится контроллер основного вида (исходная страница приложения).

Я проверил различные ответы, но ни один из них не работает - проблема с заставкой Xcode 4 и iPad2 Настройка заставок для портретного и альбомного режимов - iPad и т. Д.

Вот мой код для того же - AppDelegate.h

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    NSArray *docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath=[docDir objectAtIndex:0];
    databasePath=[docPath stringByAppendingPathComponent:@"something.sqlite"];
    //databasePath1=[docPath stringByAppendingPathComponent:@"something.sqlite"];

    NSString *bundlePath=[[NSBundle mainBundle]pathForResource:@"something" ofType:@"sqlite"];
    NSFileManager *mngr=[NSFileManager defaultManager];
    if ([mngr fileExistsAtPath:databasePath]) {
        NSLog(@"File Exists");
    }
    else
    {    
        [mngr copyItemAtPath:bundlePath toPath:databasePath error:NULL];
        NSLog(@"File Created");
    }

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

Как мне действовать сейчас? Должен ли я создать новый класс, такой как (splashScreen 1 и splashScreen 2) с uiImageView и изменить метод didFinishLaunchingWithOptions? Любая помощь будет принята с благодарностью.

Обновлено: 30 мая 2013 г.

Appdelegate.h

#import <UIKit/UIKit.h>
#import "sqlite3.h"
#import "FBInteract.h"
#import "splashScreen1.h"


sqlite3 *dbHandler;
NSString *databasePath;
@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate> {

    UIWindow *window;
    UINavigationController *naviObj;
}

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@property (strong, nonatomic) UINavigationController *naviObj;

@end

Appdelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    splashScreen1 *splashScreen1PageObj=[[splashScreen1 alloc]init];

    self.naviObj = [[UINavigationController alloc]initWithRootViewController:splashScreen1PageObj];

    self.window.rootViewController = self.naviObj; 

    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];

    [self.window makeKeyAndVisible];

    return YES;

}

splashScreen1.h и splashScreen2.h

#import <UIKit/UIKit.h>
#import "splashScreen2.h"

@interface splashScreen1 : UIViewController

{
    IBOutlet UIImageView *imgObjSplashImage; //  IBOutlet UIImageView *objSplashImage; - in splashScreen2.h

}

-(void)hideSplash;

-(void)navigationToMain;

-(void)showSplash;

@end

splashScreen1.m и splashScreen2.m

- (void)viewDidLoad
{

    // Do any additional setup after loading the view from its nib.

    [NSTimer scheduledTimerWithTimeInterval:1.2 target:self selector:@selector(showSplash) userInfo:nil repeats:NO];

    self.navigationController.navigationBarHidden=YES;

    [imgObjSplashImage setAlpha:0]; //objSplashImage instead of imgObjSplashImage in splashScreen2

    [super viewDidLoad];

}

-(void)showSplash{


    [UIImageView beginAnimations:nil context:NULL];

    [UIImageView setAnimationDuration:1.2];

    [imgObjSplashImage setAlpha:1]; //objSplashImage instead of imgObjSplashImage in splashScreen2

    [UIImageView commitAnimations];

    [NSTimer scheduledTimerWithTimeInterval:2.4 target:self selector:@selector(hideSplash) userInfo:nil repeats:NO];

}

    -(void)hideSplash{


        [UIImageView beginAnimations:nil context:NULL];

        [UIImageView setAnimationDuration:1.4];

        [imgObjSplashImage setAlpha:0]; //objSplashImage instead of imgObjSplashImage in splashScreen2

        [UIImageView commitAnimations];

        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(navigationToMain) userInfo:nil repeats:NO];

    }

    #pragma mark
#pragma mark - Navigation Coding

-(void)navigationToMain {

    //[self dismissModalViewControllerAnimated:YES];

    [self dismissViewControllerAnimated:NO completion:Nil];

    ViewController *ViewControllerPageObj=[[ViewController alloc]init];

    [self.navigationController pushViewController:ViewControllerPageObj animated:NO];

    [ViewControllerPageObj release];

    //[self presentViewController:ViewControllerPageObj animated:NO completion:Nil];

}

-(void)viewWillAppear:(BOOL)animated {

    self.navigationController.navigationBarHidden=YES;

}

Проблема в том, что ViewController(основной ViewController) не загружается... Я получаю сообщение об ошибке "сообщение отправлено освобожденному экземпляру" в части viewDidLoad ViewController.m

RootViewController -> splashScreen1 -> splashScreen2 работает нормально (все анимации исчезают и исчезают), но окончательный ViewController не загружается..

1 ответ

Для этого вам определенно нужен другой VC, давайте назовем его StartViewController. Добавьте туда imageView, вращение блока и setTimer:

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(moveOnAndChangeVC:) userInfo:nil repeats:NO];

и если вы разрабатываете приложение NavigationControl, вам также следует изменить rootVC, например:

+(void)replaceRootVCWithVC:(id)vc {
    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:[[sharedAppDelegate navigationController] viewControllers]];
    if(![viewControllers isEmpty])
        [viewControllers replaceObjectAtIndex:0 withObject:vc];
    else
        [viewControllers addObject:vc];

    [[sharedAppDelegate navigationController] setViewControllers:viewControllers];
}

РЕДАКТИРОВАТЬ:

Вы должны изменить в строке appDelegate с инициализатором:

self.viewController = [[[StartViewController alloc] initWithNibName:@"StartViewController" bundle:nil] autorelease];

Это должно вызвать ваш VC как rootVC.

Затем в StartViewController.m вы должны распознать устройство (это приложение только для iPad, верно? Не универсально) и ориентацию:

+(NSString*)recognizeDeviceAndOrientation {

    NSMutableString * returnString;
    if([StartViewController deviceInterfaceOrientation] == UIInterfaceOrientationLandscapeLeft ||    [StartViewController deviceInterfaceOrientation] == UIInterfaceOrientationLandscapeRight) {
        returnString = @"Default-Landscape";
    } else {
        returnString = @"Default-Portrait";
    }

    if([UIScreen mainScreen].scale == 2.0)
        return [NSString stringWithFormat:@"%@%@",returnString,@"@2x"];;
    else
        return returnString;
}

+(UIInterfaceOrientation)deviceInterfaceOrientation {
    return [[UIApplication sharedApplication] statusBarOrientation];
}

Это вернет вам строку с именем DefaultScreen с правильной ориентацией. Если вы работаете только с одной ориентацией, забудьте об этом.

Затем в viewDidLoad вы добавляете imageView:

- (void)viewDidLoad {
    [super viewDidLoad];    
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:[StartViewController recognizeDeviceAndOrientation]] autorelease];
   [imageView setFrame:self.frame];
   [imageView setContentMode:UIViewContentModeScaleToFill];
   [self.view addSubview:imageView];

   [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(moveOnAndChangeVC:) userInfo:nil repeats:NO];
}

Это вызовет таймер и установит imageView.

-(IBACtion)moveOnAndChangeVC:(id)sender {
   //if you using navigation app
   ViewController *vc = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
   [self.navigationController pushViewController:vc animated:NO];
}

Это будет работать И затем, если вы хотите избавиться от "кнопки назад", просто измените контроллер rootView, как я сказал в начале. Сделайте это в вашем классе ViewController.

Другие вопросы по тегам