Можно ли отобразить Default.png за указанное количество секунд? У меня есть клиент, который хочет, чтобы экран заставки отображался дольше, чем его текущее время.
Они хотели бы, чтобы он отображался в течение 2 - 3 секунд.
Можно ли отобразить Default.png за указанное количество секунд? У меня есть клиент, который хочет, чтобы экран заставки отображался дольше, чем его текущее время.
Они хотели бы, чтобы он отображался в течение 2 - 3 секунд.
Нет, при запуске приложения отображается default.png
.
Вы можете добавить новый диспетчер представлений, который отобразит default.png
в приложении didFinishLoading
.
Таким образом вы покажите default.png
немного дольше.
Вы должны показывать только default.png
, если вы загружаете данные, что может занять некоторое время.
В соответствии с инструкциями в Appstore, вы не должны откладывать запуск, который вам нужен больше, чем необходимо.
Вы также можете использовать NSThread
:
[NSThread sleepForTimeInterval:(NSTimeInterval)];
Вы можете поместить этот код в первую строку метода applicationDidFinishLaunching
.
Например, покажите default.png в течение 5 секунд.
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
[NSThread sleepForTimeInterval:5.0];
}
Добавьте это в ваше application:didFinishLaunchingWithOptions:
::
Swift:
// Delay 1 second
RunLoop.current.run(until: Date(timeIntervalSinceNow: 1.0))
Цель C:
// Delay 1 second
[[NSRunLoop currentRunLoop]runUntilDate:[NSDate dateWithTimeIntervalSinceNow: 1.0]];
Если вы используете LaunchScreen.storyboard, вы можете получить тот же контроллер представления и представить его: (не забудьте установить идентификатор раскадровки, например, "LaunchScreen")
func applicationDidBecomeActive(application: UIApplication) {
let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LaunchScreen")
self.window!.rootViewController!.presentViewController(vc, animated: false, completion: nil)
}
SWIFT 4
let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LaunchScreen")
self.window!.rootViewController!.present(vc, animated: false, completion: nil)
Этот tutorial отображает заставку в течение 2 секунд. Вы можете легко изменить его в соответствии с вашими потребностями.
- (void)showSplash {
UIViewController *modalViewController = [[UIViewController alloc] init];
modalViewController.view = modelView;
[self presentModalViewController:modalViewController animated:NO];
[self performSelector:@selector(hideSplash) withObject:nil afterDelay:yourDelay];
}
Используйте следующую строку в методе делегата didFinishLaunchingWithOptions:
:
[NSThread sleepForTimeInterval:5.0];
Он остановит экран заставки на 5,0 секунд.
Это работало для меня в Xcode 6.3.2, Swift 1.2:
import UIKit
class ViewController: UIViewController
{
var splashScreen:UIImageView!
override func viewDidLoad()
{
super.viewDidLoad()
self.splashScreen = UIImageView(frame: self.view.frame)
self.splashScreen.image = UIImage(named: "Default.png")
self.view.addSubview(self.splashScreen)
var removeSplashScreen = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "removeSP", userInfo: nil, repeats: false)
}
func removeSP()
{
println(" REMOVE SP")
self.splashScreen.removeFromSuperview()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
ViewController - это первое загружаемое приложение VC.
В Xcode 6.1, Swift 1.0, чтобы отложить запуск экрана:
Добавьте это в didFinishLaunchingWithOptions
NSThread.sleepForTimeInterval(3)
время в() является переменным.
В новом стремительном
Thread.sleep(forTimeInterval:3)
Swift 2.0:
1)
// AppDelegate.swift
import UIKit
import Foundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var splashTimer:NSTimer?
var splashImageView:UIImageView?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIApplication.sharedApplication().delegate!.window!
let splashImage: UIImage = UIImage(named: "ic_120x120.png")!
splashImageView = UIImageView(image: splashImage)
splashImageView!.frame = CGRectMake(0, 0, (window?.frame.width)!, (window?.frame.height)!)
window!.addSubview(splashImageView!)
window!.makeKeyAndVisible()
//Adding splash Image as UIWindow subview.
window!.bringSubviewToFront(window!.subviews[0])
// Here specify the timer.
splashTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "splashTimerForLoadingScreen", userInfo: nil, repeats: true)
return true
}
func splashTimerForLoadingScreen() {
splashImageView!.removeFromSuperview()
splashTimer!.invalidate()
}
2)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NSThread.sleepForTimeInterval(9)
OR
sleep(9)
return true
}
3) Использование концепции контроллера корневого представления:
// AppDelegate.swift
import UIKit
import Foundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var splashTimer:NSTimer?
var storyboard:UIStoryboard?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.makeKeyAndVisible()
storyboard = UIStoryboard(name: "Main", bundle: nil)
//Here set the splashScreen VC
let rootController = storyboard!.instantiateViewControllerWithIdentifier("secondVCID")
if let window = self.window {
window.rootViewController = rootController
}
//Set Timer
splashTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "splashTimerCrossedTimeLimit", userInfo: nil, repeats: true)
return true
}
func splashTimerCrossedTimeLimit(){
//Here change the root controller
let rootController = storyboard!.instantiateViewControllerWithIdentifier("firstVCID")
if let window = self.window {
window.rootViewController = rootController
}
splashTimer?.invalidate()
}
В Swift 4.0
Задержка в 1 секунду после времени запуска по умолчанию...
RunLoop.current.run(until: Date(timeIntervalSinceNow : 1.0))
Вы можете использовать следующий код:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSMutableString *path = [[NSMutableString alloc]init];
[path setString:[[NSBundle mainBundle] resourcePath]];
[path setString:[path stringByAppendingPathComponent:@"Default.png"]];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
[path release];
UIImageView *imageView=[[UIImageView alloc]initWithImage:image];
imageView.frame=CGRectMake(0, 0, 320, 480);
imageView.tag = 2;
[window addSubview:imageView];
[window makeKeyAndVisible];
// Here specify the time limit.
timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(timerForLoadingScreen) userInfo:nil repeats:YES];
}
-(void)timerForLoadingScreen
{
[timer invalidate];
if ([window viewWithTag:2]!=nil)
{
[[window viewWithTag:2]removeFromSuperview];
}
// Your any other initialization code that you wish to have in didFinishLaunchingWithOptions
}
Swift 3
Это можно сделать безопасным способом, представив контроллер splash для того, что когда-либо вы укажете, затем удалите его и покажите свой обычный rootViewController.
В AppDelegate вы можете создать эти 2 метода:
private func extendSplashScreenPresentation(){
// Get a refernce to LaunchScreen.storyboard
let launchStoryBoard = UIStoryboard.init(name: "LaunchScreen", bundle: nil)
// Get the splash screen controller
let splashController = launchStoryBoard.instantiateViewController(withIdentifier: "splashController")
// Assign it to rootViewController
self.window?.rootViewController = splashController
self.window?.makeKeyAndVisible()
// Setup a timer to remove it after n seconds
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(dismissSplashController), userInfo: nil, repeats: false)
}
2.
@objc private func dismissSplashController() {
// Get a refernce to Main.storyboard
let mainStoryBoard = UIStoryboard.init(name: "Main", bundle: nil)
// Get initial viewController
let initController = mainStoryBoard.instantiateViewController(withIdentifier: "initController")
// Assign it to rootViewController
self.window?.rootViewController = initController
self.window?.makeKeyAndVisible()
}
Теперь вы вызываете
self.extendSplashScreenPresentation()
in didFinishLaunchingWithOptions.
Вы настроены для перехода...
Напишите sleep(5.0)
в - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
в течение 5 секунд будет отображаться экран заставки
1. Добавить другой контроллер представления в "doneFinishLaunchingWithOptions"
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UINavigationController *homeNav = [storyboard instantiateViewControllerWithIdentifier:@"NavigationControllerView"];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"SplashViewController"];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = homeNav;
[self.window makeKeyAndVisible];
[(UINavigationController *)self.window.rootViewController pushViewController:viewController animated:NO];
}
2.В просмотре загрузился контроллер SplashView
[self performSelector:@selector(removeSplashScreenAddViewController) withObject:nil afterDelay:2.0];
3. В методе removeSplashScreenAddViewController вы можете добавить свой главный контроллер вида, например.
- (void) removeSplashScreenAddViewController {` UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UINavigationController *homeNav = [storyboard instantiateViewControllerWithIdentifier:@"HomeNav"];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:viewControllerName];
UIWindow *window = [StaticHelper mainWindow];
window.rootViewController = homeNav;
[window makeKeyAndVisible];
[(UINavigationController *)window.rootViewController pushViewController:viewController animated:NO];`}
Самый простой способ добиться этого - создать UIImageView
с "Default.png" в верхней части вашего первого ViewController UIView
.
И добавьте таймер, чтобы удалить UIImageView
после секунд, ожидаемых.
Поместите ваш default.png в полноэкранный режим UIImageView в виде подвью в верхней части основного вида, таким образом, охватывая ваш другой интерфейс. Установите таймер, чтобы удалить его через х секунд (возможно с эффектами), показывая ваше приложение.
Это работает...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Load Splash View Controller first
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"Splash"];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
// Load other stuff that requires time
// Now load the main View Controller that you want
}
Самое простое решение здесь - это добавить sleep()
к методу didFinishLaunchingWithOptions
в вашем классе AppDelegate
.
Свифт 4:
sleep(1)
Если вы хотите сделать что-то более интересное, вы также можете расширить текущий RunLoop тем же методом:
Свифт 4:
RunLoop.current.run(until: Date(timeIntervalSinceNow: 1))
Просто запустите название проекта. затем щелкните правой кнопкой мыши/свойства/вкладку приложения.
Найдите "Просмотреть события приложения" рядом с полем "Слэш".
скопируйте этот код в myApplication
Класс:
Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
System.Threading.Thread.Sleep(3000) ' or other time
End Sub
Вы можете создать свое собственное представление и отобразить его, когда приложение запустится, и скрыть его таймером. Пожалуйста, не задерживайте запуск приложения как свою плохую идею.
В Swift 4.2
Для задержки 1 секунда после времени запуска по умолчанию...
Thread.sleep(forTimeInterval: 1)
Вы можете просто указать количество секунд для сна в методе AppDelegate didFinishLaunchingWithOptions.
Или, альтернативно, используйте другой ImageView для настройки заставки.
Подробнее см. подробности по следующей ссылке: