Can't show next view controller while using coordinator pattern - ios

I am trying to use coordinator in my project.
I want to show next viewController on button click.
My code goes to navigationController.pushViewController(registrationViewController, animated: true) but nothing happens
My FirstViewController
class AuthViewController: UIViewController {
private var registrationCoordinator: RegistrationCoordinator?
...
#objc func registrationButtonPressed() {
registrationCoordinator = RegistrationCoordinator(navigationController: UINavigationController())
registrationCoordinator?.start()
}
}
My Coordinator
class RegistrationCoordinator {
private let navigationController: UINavigationController
var authViewController: AuthViewController?
//Init
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
//Functions
public func start() {
showRegistrationViewController()
}
private func showRegistrationViewController() {
let registrationViewController = RegistrationViewController()
navigationController.isNavigationBarHidden = true
registrationViewController.view.backgroundColor = .orange
navigationController.pushViewController(registrationViewController, animated: true)
}
}
My SceneDelegate
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var authCoordinator: AuthCoordinator?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
let rootWindow = UIWindow(windowScene: windowScene)
let navigationController = UINavigationController()
authCoordinator = AuthCoordinator(navigationController: navigationController)
window = rootWindow
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
authCoordinator?.start()
}

#objc func registrationButtonPressed() {
registrationCoordinator = RegistrationCoordinator(navigationController:
UINavigationController())
registrationCoordinator?.start() }
When you call your coordinator you are instantiating the navigation controller.
Then you are using your navigation controller to push a viewcontroller, but yout navigation controller isn't in the view herarchy, not in the main window, not inside other view.
In other words, your navigation controller exists, but is not part of the interface. Therefore nothing it does would be shown.
You are not passing the same Navigation Controller you use in the SceneDelegate, you are creating a new one.
You can pass to the coordinator the navigation controller of your current viewcontroller.
registrationCoordinator =
RegistrationCoordinator(navigationController:
self.navigationController?)
That, of course, assuming that your current viewcontroller has a navigation controller (and your coordinator would have to accept optionals)

Related

when need to switch the rootViewController

I've been working on a Swift project and I have two view controllers, the login view controller & the home view controller. When a user launches the app, I want to display the login view controller if the user is not logged in, on the other hand, if the user is logged in, I want to display the home view controller.
So the flow is gonna be something like this.
When the user is not logged in, display
LoginViewController
HomeViewController
When the user is already logged in, display
HomeViewController
In the scene delegate, I've written
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let scene = (scene as? UIWindowScene) else { return }
window = UIWindow(frame: scene.coordinateSpace.bounds)
window?.windowScene = scene
window?.rootViewController = HomeViewController() or LoginViewController() depending on the user's login status
window?.makeKeyAndVisible()
}
I was wondering if I should apply the HomeViewController as a rootviewcontroller regardless of the user's login status (and maybe present loginVC on the homeVC when the user is not logged in), or I should switch the view controller depending on the user's login status.
So, in this case, what is the point of switching rootviewcontroller? and why it is (or isn't important) to switch the root view controller?
Is there anything I should consider when I apply view controller to the root viewcontroller property?
// SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
// if user is logged in before
if let loggedUsername = UserDefaults.standard.string(forKey: "username") {
window?.rootViewController = HomeViewController()
} else {
// if user isn't logged in
window?.rootViewController = LoginViewController()
}
}
I think there can be another cases, like RootVC is a container ViewContoller consists of HomeVC and LoginVC.
example)
final class RootVC: UIViewController {
private let loginVC = LoginVC()
private let homeVC = HomeVC()
override func viewDidLoad() {
super.viewDidLoad()
addChild(homeVC)
view.addSubview(homeVC.view)
addChild(loginVC)
view.addSubview(loginVC.view)
}
func showVC() {
if isLogin {
homeVC.hide()
loginVC.show()
} else {
reverse()
}
}
}
Hi all i have one idea for set a RootViewController in SceneDelegate. First we need to create the method setViewController and variable currentScene in SceneDelegate class kindly feel free to refer the code below.
Two different viewcontroller as per your example HomeViewController, LoginViewController
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var currentScene: UIScene?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
currentScene = scene
if UserDefaults.standard.bool(forKey: "isLoggedIn") == true{
self.setRootViewController(LoginViewController())
}else{
self.setRootViewController(HomeViewController())
}
}
func setRootViewController(_ viewController: UIViewController){
guard let scene = (currentScene as? UIWindowScene) else { return }
window = UIWindow(frame: scene.coordinateSpace.bounds)
window?.windowScene = scene
window?.rootViewController = viewController
window?.makeKeyAndVisible()
}
}
class ButtonViewController: UIViewController {
lazy var button: UIButton! = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .darkGray
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
button.tag = 1
button.setTitle("Tap", for: .normal)
return button
}()
override func loadView() {
super.loadView()
self.view.backgroundColor = .white
setConstraint()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func setConstraint(){
self.view.addSubview(self.button)
NSLayoutConstraint.activate([
self.button.heightAnchor.constraint(equalToConstant: 60),
self.button.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width * 0.66),
self.button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
self.button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
])
}
#objc func buttonAction(){ }
}
class HomeViewController: ButtonViewController{
override func loadView() {
super.loadView()
self.view.backgroundColor = .red
self.button.setTitle(String(describing: HomeViewController.self), for: .normal)
}
override func buttonAction() {
let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as! SceneDelegate
sceneDelegate.setRootViewController(LoginViewController())
}
}
class LoginViewController: ButtonViewController{
override func loadView() {
super.loadView()
self.view.backgroundColor = .green
self.button.setTitle(String(describing: LoginViewController.self), for: .normal)
}
override func buttonAction() {
let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as! SceneDelegate
sceneDelegate.setRootViewController(HomeViewController())
}
}
If click the button view controller can be change as rootViewController.
Output:

Trying to find a better approach to custom tab bar

I'm trying to create a custom TabBar.
My approach so far, was to create one UIViewController (Let's call it the TabBarController), In the TabBarController, I added a childVC (Let's call it UserViewController).
I couldn't figure out a way to change the UserViewController without making the TabBarController to disappear.
I started to think maybe this is not a good option, and that there most be a better, actually working way to do so.
All I really trying to achieve is a TabBarController, separated from the UserViewController, the TabBarController will always be displayed on the bottom of the screen, and by clicking the items in it, the UserViewController will change accordingly.
I searched for hours, tried different solutions, nothing worked. Really hope you could guide me, maybe share a tutorial or article you have about this.
Create a subclass of UITabBarViewController.
class TabBarController: UITabBarController {
var previousTabIndex: Int?
override func viewDidLoad() {
super.viewDidLoad()
let viewControllerOne = ViewController()
viewControllerOne.tabBarItem.image = UIImage(named: "one")
viewControllerOne.tabBarItem.title = "One"
let viewControllerTwo = ViewController()
viewControllerTwo.tabBarItem.image = UIImage(named: "two")
viewControllerTwo.tabBarItem.title = "Two"
let viewControllerThree = ViewController()
viewControllerThree.tabBarItem.title = "Premium"
viewControllerThree.tabBarItem.image = UIImage(named: "three")
let tabBarList = [
viewControllerOne,
viewControllerTwo,
viewControllerThree
]
self.viewControllers = tabBarList.map {
let nav = UINavigationController(rootViewController: $0)
return nav
}
}
}
And then in SceneDelegate, set window.rootViewController = TabBarController()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = TabBarController()
self.window = window
window.makeKeyAndVisible()
}
}
If you have created your project in older version of xCode, assign TabBarController() to window.rootController in didFinishLaunchingWithOptions of AppDelegate

How can I put the initialViewController in code from AppDelegate? SWIFT [duplicate]

Creating a new project in XCode 6 doesn't allow to disable Storyboards. You can only select Swift or Objective-C and to use or not Core Data.
I tried deleting the storyboard and from the project removing the main storyboard and manually setting the window from didFinishLaunching
In the AppDelegate I have this:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow
var testNavigationController: UINavigationController
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
testNavigationController = UINavigationController()
var testViewController: UIViewController = UIViewController()
self.testNavigationController.pushViewController(testViewController, animated: false)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window.rootViewController = testNavigationController
self.window.backgroundColor = UIColor.whiteColor()
self.window.makeKeyAndVisible()
return true
}
}
However, XCode gives me an error:
Class 'AppDelegate' has no initializers
Anyone has succeed in this?
All it takes for not using Storyboards for the rootViewController:
1· Change AppDelegate.swift to:
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if let window = window {
window.backgroundColor = UIColor.white
window.rootViewController = ViewController()
window.makeKeyAndVisible()
}
return true
}
}
2· Create a ViewController subclass of UIViewController:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
}
}
3· If you created the project from an Xcode template:
Remove the key-value pair for key "Main storyboard file base name" from Info.plist.
Delete the storyboard file Main.storyboard.
As you can see in the first code snippet, instead of implicitly unwrapping an optional, I rather like the if let syntax for unwrapping the optional window property. Here I'm using it like if let a = a { } so that the optional a becomes a non-optional reference inside the if-statement with the same name – a.
Finally self. is not necessary when referencing the window property inside it own class.
You must mark the window and testNavigationController variables as optional:
var window : UIWindow?
var testNavigationController : UINavigationController?
Swift classes require non-optional properties to be initialized during the instantiation:
Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.
Properties of optional type are automatically initialized with a value of nil, indicating that the property is deliberately intended to have “no value yet” during initialization.
When using optional variables, remember to unwrap them with !, such as:
self.window!.backgroundColor = UIColor.whiteColor();
If you want to Initialize your viewController with xib and and need to use navigation controller. Here is a piece of code.
var window: UIWindow?
var navController:UINavigationController?
var viewController:ViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
viewController = ViewController(nibName: "ViewController", bundle: nil);
navController = UINavigationController(rootViewController: viewController!);
window?.rootViewController = navController;
window?.makeKeyAndVisible()
return true
}
Try the following code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
// Create a nav/vc pair using the custom ViewController class
let nav = UINavigationController()
let vc = NextViewController ( nibName:"NextViewController", bundle: nil)
// Push the vc onto the nav
nav.pushViewController(vc, animated: false)
// Set the window’s root view controller
self.window!.rootViewController = nav
// Present the window
self.window!.makeKeyAndVisible()
return true
}
I have found the answer it had nothing to do with the xcode setup, removing storyboard and the reference from project is the right thing. It had to do with the swift syntax.
The code is the following:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var testNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.testNavigationController = UINavigationController()
var testViewController: UIViewController? = UIViewController()
testViewController!.view.backgroundColor = UIColor.redColor()
self.testNavigationController!.pushViewController(testViewController, animated: false)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = testNavigationController
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
}
You can just do it like this:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var IndexNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
var IndexViewContoller : IndexViewController? = IndexViewController()
self.IndexNavigationController = UINavigationController(rootViewController:IndexViewContoller)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = self.IndexNavigationController
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
}
Updated for Swift 3.0:
window = UIWindow()
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
Update: Swift 5 and iOS 13:
Create a Single View Application.
Delete Main.storyboard (right-click and delete).
Delete Storyboard Name from the default scene configuration in the Info.plist file:
Open SceneDelegate.swift and change func scene from:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
to
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).x
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = ViewController()
self.window = window
window.makeKeyAndVisible()
}
}
I recommend you use controller and xib
MyViewController.swift and MyViewController.xib
(You can create through File->New->File->Cocoa Touch Class and set "also create XIB file" true, sub class of UIViewController)
class MyViewController: UIViewController {
.....
}
and In AppDelegate.swift func application write the following code
....
var controller: MyViewController = MyViewController(nibName:"MyViewController",bundle:nil)
self.window!.rootViewController = controller
return true
It should be work!
Here is a complete swift test example for an UINavigationController
import UIKit
#UIApplicationMain
class KSZAppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var testNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Working WITHOUT Storyboard
// see http://randexdev.com/2014/07/uicollectionview/
// see http://stackoverflow.com/questions/24046898/how-do-i-create-a-new-swift-project-without-using-storyboards
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let win = window {
win.opaque = true
//you could create the navigation controller in the applicationDidFinishLaunching: method of your application delegate.
var testViewController: UIViewController = UIViewController()
testNavigationController = UINavigationController(rootViewController: testViewController)
win.rootViewController = testNavigationController
win.backgroundColor = UIColor.whiteColor()
win.makeKeyAndVisible()
// see corresponding Obj-C in https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewControllerCatalog/Chapters/NavigationControllers.html#//apple_ref/doc/uid/TP40011313-CH2-SW1
// - (void)applicationDidFinishLaunching:(UIApplication *)application {
// UIViewController *myViewController = [[MyViewController alloc] init];
// navigationController = [[UINavigationController alloc]
// initWithRootViewController:myViewController];
// window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// window.rootViewController = navigationController;
// [window makeKeyAndVisible];
//}
}
return true
}
}
Why don't you just create an empty application? the storyboard is not created to me...
We can create navigation-based application without storyboard in Xcode 6 (iOS 8) like as follows:
Create an empty application by selecting the project language as
Swift.
Add new cocoa touch class files with the interface xib. (eg.
TestViewController)
In the swift we have only one file interact with the xib i.e. *.swift
file, there is no .h and .m files.
We can connect the controls of xib with swift file same as in iOS 7.
Following are some snippets for work with the controls and Swift
//
// TestViewController.swift
//
import UIKit
class TestViewController: UIViewController {
#IBOutlet var testBtn : UIButton
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
#IBAction func testActionOnBtn(sender : UIButton) {
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the action.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
NSLog("The simple alert's cancel action occured.")
}
// Add the action.
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Changes in AppDelegate.swift file
//
// AppDelegate.swift
//
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
var testController: TestViewController? = TestViewController(nibName: "TestViewController", bundle: nil)
self.navigationController = UINavigationController(rootViewController: testController)
self.window!.rootViewController = self.navigationController
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
}
Find code sample and other information on
http://ashishkakkad.wordpress.com/2014/06/16/create-a-application-in-xcode-6-ios-8-without-storyborard-in-swift-language-and-work-with-controls/
In iOS 13 and above when you create new project without storyboard use below steps:
Create project using Xcode 11 or above
Delete storyboard nib and class
Add new new file with xib
Need to set root view as UINavigationController SceneDelegate
add below code:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// guard let _ = (scene as? UIWindowScene) else { return }
if let windowScene = scene as? UIWindowScene {
self.window = UIWindow(windowScene: windowScene)
let mainController = HomeViewController() as HomeViewController
let navigationController = UINavigationController(rootViewController: mainController)
self.window!.rootViewController = navigationController
self.window!.makeKeyAndVisible()
}
}

Swift – Instantiating a navigation controller without storyboards in App Delegate

I'm rebuilding an app without storyboards and the part of it that I'm having the most trouble with is navigating view-to-view programatically. Few things are written out there which don't use storyboards, so finding an answer for this has been tough.
My problem is pretty simple. I have my ViewController and my SecondViewController and I want to push from the former to the latter.
In AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
return true
}
Then in ViewController.swift:
class ViewController: UIViewController, AVAudioPlayerDelegate, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
startFinishButton.setTitle("Begin", forState: .Normal)
startFinishButton.addTarget(self, action: "moveToSecondViewController", forControlEvents: .TouchUpInside)
view.addSubview <*> startFinishButton
}
func moveToSecondViewController(sender: UIButton) {
let vc = SecondViewController()
println(self.navigationController) // returns nil
self.navigationController?.pushViewController(vc, animated: true)
}
}
Printing self.navigationController returns nil. I've tried doing:
var navController = UINavigationController() when the ViewController class is created (but outside of ViewDidLoad, right under the class declaration) and done the push using the navController var but that hasn't worked.
I'm thinking maybe the solution is to create a navigation controller in App Delegate that the whole app would use, I guess as a global variable?
My hope is that this post can serve many others who are new to Swift and want to remove storyboards from their app.
Thanks for taking a look and for your help.
In Swift 3
Place this code inside didFinishLaunchingWithOptions method in AppDelegate class.
window = UIWindow(frame: UIScreen.main.bounds)
let mainController = MainViewController() as UIViewController
let navigationController = UINavigationController(rootViewController: mainController)
navigationController.navigationBar.isTranslucent = false
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
In AppDelegate
var window: UIWindow?
var navController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
navController = UINavigationController()
var viewController: ViewController = ViewController()
self.navController!.pushViewController(viewController, animated: false)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = navController
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
In ViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "FirstVC"
var startFinishButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
startFinishButton.frame = CGRectMake(100, 100, 100, 50)
startFinishButton.backgroundColor = UIColor.greenColor()
startFinishButton.setTitle("Test Button", forState: UIControlState.Normal)
startFinishButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(startFinishButton)
}
func buttonAction(sender:UIButton!)
{
println("Button tapped")
let vc = SecondViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In Swift 5 and Xcode 13 there is a SceneDelegate along with the AppDelegate. So now to completely remove the storyboard from a project and embed the view controller in a navigation controller do the following:
Delete the actual storyboard in the Project Navigator
Select the project in the Project Navigator, select Target and then the General tab, then delete the storyboard from Main Interface
In the info.plist file delete the storyboard from:
Application Scene Manifest > Scene Configuration > Application Session Role > Item 0 (Default Configuration) > Storyboard Name
Then in the scene delegate change the scene function to look like this:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
let window = UIWindow(windowScene: windowScene)
let navigationController = UINavigationController(rootViewController: YourViewController())
window.rootViewController = navigationController
self.window = window
window.makeKeyAndVisible()
}

How do I create a new Swift project without using Storyboards?

Creating a new project in XCode 6 doesn't allow to disable Storyboards. You can only select Swift or Objective-C and to use or not Core Data.
I tried deleting the storyboard and from the project removing the main storyboard and manually setting the window from didFinishLaunching
In the AppDelegate I have this:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow
var testNavigationController: UINavigationController
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
testNavigationController = UINavigationController()
var testViewController: UIViewController = UIViewController()
self.testNavigationController.pushViewController(testViewController, animated: false)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window.rootViewController = testNavigationController
self.window.backgroundColor = UIColor.whiteColor()
self.window.makeKeyAndVisible()
return true
}
}
However, XCode gives me an error:
Class 'AppDelegate' has no initializers
Anyone has succeed in this?
All it takes for not using Storyboards for the rootViewController:
1· Change AppDelegate.swift to:
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if let window = window {
window.backgroundColor = UIColor.white
window.rootViewController = ViewController()
window.makeKeyAndVisible()
}
return true
}
}
2· Create a ViewController subclass of UIViewController:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
}
}
3· If you created the project from an Xcode template:
Remove the key-value pair for key "Main storyboard file base name" from Info.plist.
Delete the storyboard file Main.storyboard.
As you can see in the first code snippet, instead of implicitly unwrapping an optional, I rather like the if let syntax for unwrapping the optional window property. Here I'm using it like if let a = a { } so that the optional a becomes a non-optional reference inside the if-statement with the same name – a.
Finally self. is not necessary when referencing the window property inside it own class.
You must mark the window and testNavigationController variables as optional:
var window : UIWindow?
var testNavigationController : UINavigationController?
Swift classes require non-optional properties to be initialized during the instantiation:
Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.
Properties of optional type are automatically initialized with a value of nil, indicating that the property is deliberately intended to have “no value yet” during initialization.
When using optional variables, remember to unwrap them with !, such as:
self.window!.backgroundColor = UIColor.whiteColor();
If you want to Initialize your viewController with xib and and need to use navigation controller. Here is a piece of code.
var window: UIWindow?
var navController:UINavigationController?
var viewController:ViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
viewController = ViewController(nibName: "ViewController", bundle: nil);
navController = UINavigationController(rootViewController: viewController!);
window?.rootViewController = navController;
window?.makeKeyAndVisible()
return true
}
Try the following code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
// Create a nav/vc pair using the custom ViewController class
let nav = UINavigationController()
let vc = NextViewController ( nibName:"NextViewController", bundle: nil)
// Push the vc onto the nav
nav.pushViewController(vc, animated: false)
// Set the window’s root view controller
self.window!.rootViewController = nav
// Present the window
self.window!.makeKeyAndVisible()
return true
}
I have found the answer it had nothing to do with the xcode setup, removing storyboard and the reference from project is the right thing. It had to do with the swift syntax.
The code is the following:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var testNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.testNavigationController = UINavigationController()
var testViewController: UIViewController? = UIViewController()
testViewController!.view.backgroundColor = UIColor.redColor()
self.testNavigationController!.pushViewController(testViewController, animated: false)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = testNavigationController
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
}
You can just do it like this:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var IndexNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
var IndexViewContoller : IndexViewController? = IndexViewController()
self.IndexNavigationController = UINavigationController(rootViewController:IndexViewContoller)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = self.IndexNavigationController
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
}
Updated for Swift 3.0:
window = UIWindow()
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
Update: Swift 5 and iOS 13:
Create a Single View Application.
Delete Main.storyboard (right-click and delete).
Delete Storyboard Name from the default scene configuration in the Info.plist file:
Open SceneDelegate.swift and change func scene from:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
to
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).x
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = ViewController()
self.window = window
window.makeKeyAndVisible()
}
}
I recommend you use controller and xib
MyViewController.swift and MyViewController.xib
(You can create through File->New->File->Cocoa Touch Class and set "also create XIB file" true, sub class of UIViewController)
class MyViewController: UIViewController {
.....
}
and In AppDelegate.swift func application write the following code
....
var controller: MyViewController = MyViewController(nibName:"MyViewController",bundle:nil)
self.window!.rootViewController = controller
return true
It should be work!
Here is a complete swift test example for an UINavigationController
import UIKit
#UIApplicationMain
class KSZAppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var testNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Working WITHOUT Storyboard
// see http://randexdev.com/2014/07/uicollectionview/
// see http://stackoverflow.com/questions/24046898/how-do-i-create-a-new-swift-project-without-using-storyboards
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let win = window {
win.opaque = true
//you could create the navigation controller in the applicationDidFinishLaunching: method of your application delegate.
var testViewController: UIViewController = UIViewController()
testNavigationController = UINavigationController(rootViewController: testViewController)
win.rootViewController = testNavigationController
win.backgroundColor = UIColor.whiteColor()
win.makeKeyAndVisible()
// see corresponding Obj-C in https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewControllerCatalog/Chapters/NavigationControllers.html#//apple_ref/doc/uid/TP40011313-CH2-SW1
// - (void)applicationDidFinishLaunching:(UIApplication *)application {
// UIViewController *myViewController = [[MyViewController alloc] init];
// navigationController = [[UINavigationController alloc]
// initWithRootViewController:myViewController];
// window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// window.rootViewController = navigationController;
// [window makeKeyAndVisible];
//}
}
return true
}
}
Why don't you just create an empty application? the storyboard is not created to me...
We can create navigation-based application without storyboard in Xcode 6 (iOS 8) like as follows:
Create an empty application by selecting the project language as
Swift.
Add new cocoa touch class files with the interface xib. (eg.
TestViewController)
In the swift we have only one file interact with the xib i.e. *.swift
file, there is no .h and .m files.
We can connect the controls of xib with swift file same as in iOS 7.
Following are some snippets for work with the controls and Swift
//
// TestViewController.swift
//
import UIKit
class TestViewController: UIViewController {
#IBOutlet var testBtn : UIButton
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
#IBAction func testActionOnBtn(sender : UIButton) {
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the action.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
NSLog("The simple alert's cancel action occured.")
}
// Add the action.
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Changes in AppDelegate.swift file
//
// AppDelegate.swift
//
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
var testController: TestViewController? = TestViewController(nibName: "TestViewController", bundle: nil)
self.navigationController = UINavigationController(rootViewController: testController)
self.window!.rootViewController = self.navigationController
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
}
Find code sample and other information on
http://ashishkakkad.wordpress.com/2014/06/16/create-a-application-in-xcode-6-ios-8-without-storyborard-in-swift-language-and-work-with-controls/
In iOS 13 and above when you create new project without storyboard use below steps:
Create project using Xcode 11 or above
Delete storyboard nib and class
Add new new file with xib
Need to set root view as UINavigationController SceneDelegate
add below code:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// guard let _ = (scene as? UIWindowScene) else { return }
if let windowScene = scene as? UIWindowScene {
self.window = UIWindow(windowScene: windowScene)
let mainController = HomeViewController() as HomeViewController
let navigationController = UINavigationController(rootViewController: mainController)
self.window!.rootViewController = navigationController
self.window!.makeKeyAndVisible()
}
}

Resources