move to next view controller programmatically - swift

I wonder how to create a function that move to the login page after click login button, with code/programmatic way.
There is my code:
final class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let loginButton = UIButton(frame: CGRectMake(20, 640, 175, 75))
loginButton.setTitle("Login", forState: UIControlState.Normal)
loginButton.backgroundColor = UIColor.init(red: 255, green: 215, blue: 0, alpha: 0.8)
loginButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
loginButton.titleLabel!.font = UIFont(name: "StarJediSpecialEdition", size: 30)
loginButton.addTarget(self,
action: #selector(ViewController.tapActionButton),
forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(loginButton)
}
func tapActionButton(sender:UIButton!) {
print("Button is working")
}
}

There are multiple ways how you create your login page UIViewController:
From xib, for example, you can inherit your controller from this class:
class XibLoadedVC: UIViewController {
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
required init() {
print("init \(type(of: self))")
let bundle = Bundle(for: type(of: self))
super.init(nibName: String(describing: type(of: self)), bundle: bundle)
}
}
or just
let controller = LoginPageViewController(nibName: "LoginPageViewController", bundle: nil)
From storyboard:
let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let loginPage = storyboard.instantiateViewControllerWithIdentifier("LoginPageViewController") as! LoginPageViewController
There are multiple ways to show controller depending on how you are create it:
You can just present controller with:
func tapActionButton(sender: UIButton!) {
let loginPage = LoginPageViewController()
self.present(loginPage, animated: true)
}
Programmatically push using navigationController:
navigationController?.pushViewController(loginPage, animated: true)
Requires UINavigationController to work. As you can’t be sure, is your controller inside navigation controller stack or not, there is optional navigationController? to not crush the app :)
Storyboard and Segues:
Create segue between your ViewController and LoginPageViewController.
Give your segue an identifier and also presentation style. For this case it will be Show
Now in your ViewController override below method
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "YourSegueIdentifier"
let loginPage = segue.destinationViewController as! LoginPageViewController
}
}
On loginButton tap action:
func tapActionButton(sender: UIButton!) {
performSegueWithIdentifier("YourSegueIdentifier", sender: nil)
}
And you are done.
P.S.
Also, there is modern SwiftUI way to do all that, you can look into tutorials and official documentation.

You need to create an instance of the next view controller and then either present or push that view controller
To present modally:
self.presentViewController(nextVC, animated: true, completion: nil)
or to push:
self.navigationController?.pushViewController(nextVC, animated: true)
all that stuff with segues apply to storyboards
Cheers!

Related

delegate to Storyboard created View Controller

i created two projects to learn how the delegate method is working..
one project created WITHOUT storyboard, just via code and my delegate is working just fine.
i built the other Project WITH storyboard, which means all ViewControllers are visible in the Interfacebuilder..
i am sure the issue lays in the definition of the ViewControllers in the code file:
let homeVC = HomeViewController()
Can someone please tell what is wrong here?
import UIKit
protocol HomeViewControllerDelegate: AnyObject {
func showMenu()
}
class HomeViewController: UIViewController {
var delegate: HomeViewControllerDelegate?
override func viewDidLoad() {
title = "App"
super.viewDidLoad()
configureNaviBar()
}
func configureNaviBar() {
// Left Bar Button Item
let burgerButton = UIImage(systemName: "line.horizontal.3")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: burgerButton, style: .plain, target: self, action: #selector(showMenu))
}
#objc func showMenu(sender: AnyObject) {
print("show Menu (home)")
// homeDelegate is nil?
delegate!.showMenu() // throws an error!
}
}
import UIKit
class MainViewController: UIViewController {
let naviVC:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NaviVC") as! NaviVC
let menuVC:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SideMenuID") as! SideMenuViewController
let homeVC = HomeViewController()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
setupContainerView()
}
func setupContainerView() {
// menu
addChild(menuVC)
self.view.addSubview(menuVC.view)
menuVC.view.frame = CGRect(x: 0, y: 0, width: 200, height: 896)
menuVC.didMove(toParent: self)
// Home
homeVC.delegate = self
addChild(naviVC)
self.view.addSubview(naviVC.view)
naviVC.view.frame = self.view.bounds
naviVC.didMove(toParent: self)
}
}
extension MainViewController: HomeViewControllerDelegate {
func showMenu() {
// does not get called
print("did tap menu")
}
}
Error:
Debug_project/HomeViewController.swift:49: Fatal error: Unexpectedly found nil while unwrapping an Optional value
i am already searching for days now, and just can't find the solution for this...
please help me out guys
I found the solution!
Tanks to Phillip Mills and all others for helping me find this..
the solution is:
change
let homeVC = HomeViewController()
to
override func viewDidLoad() {
super.viewDidLoad()
let homeVC = naviVC.viewControllers.first as! HomeViewController // working: this is it!
}
class MainViewController: UIViewController {
let naviVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NaviVC") as! NaviVC
let menuVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SideMenuID") as! SideMenuViewController
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
setupContainerView()
}
func setupContainerView() {
// menu
addChild(menuVC)
self.view.addSubview(menuVC.view)
menuVC.view.frame = CGRect(x: 0, y: 0, width: 200, height: 896)
menuVC.didMove(toParent: self)
// Home
let homeVC = naviVC.viewControllers.first as! HomeViewController // working: this is it!
homeVC.delegate = self
addChild(naviVC)
self.view.addSubview(naviVC.view)
naviVC.view.frame = self.view.bounds
naviVC.didMove(toParent: self)
}
}
extension MainViewController: HomeViewControllerDelegate {
func showMenu() {
// does not get called
print("did tap menu")
}
}

How to know when VC2 was dismissed on VC1?

I have ViewController1 that goes to ViewModel and then to Coordinator to present ViewController2.
The problem is: I need to know when VC2 was dismissed on VC1.
What I need to do: When VC2 is dismissed, I need to reload my table from VC1.
I can not use Delegate since I cant communicate between then (because of Coordinator).
Any help please?
Adding some code: My Coordinator:
public class Coordinator: CoordinatorProtocol {
public func openVC1() {
let viewModel = ViewModel1(coordinator: self)
guard let VC1 = ViewControllerOne.instantiate(storyboard: storyboard, viewModel: viewModel) else {
return
}
navigationController?.pushViewController(VC1, animated: true)
}
public func openVC2() {
let viewModel = ViewModel2()
guard let alertPriceDeleteVC = ViewControllerTwo.instantiate(storyboard: storyboard, viewModel: viewModel) else {
return
}
let nav = UINavigationController(rootViewController: VC2)
navigationController?.present(nav, animated: true, completion: nil)
}
CoordinatorProtocol:
public protocol CoordinatorProtocol {
func openVC1()
func openVC2()
}
My ViewModel1 calling VC2 through coordinatorDelegate:
func openVC2() {
coordinator.openVC2()
}
What I do when I finish ViewController2 and send user back do VC1:
navigationController?.dismiss(animated: true, completion: nil)
You need to to assign delegate value from prepare. Or you can assign delegate with initialize RedScreenVC(self) from your ViewController if u don't want to use storyboard/xib.
import UIKit
class ViewController: UIViewController, NavDelegate {
func navigate(text: String, isShown: Bool) {
print("text: \(text) isShown: \(isShown)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "RedScreenVC") {
let redScreenVC = segue.destination as? RedScreenVC
redScreenVC?.delegate = self
}
}
#IBAction func nextPageButtonEventLustener(_ sender: Any) {
performSegue(withIdentifier: "RedScreenVC", sender: sender)
}
}
import UIKit
protocol NavDelegate {
func navigate(text: String, isShown: Bool)
}
class RedScreenVC: UIViewController {
weak var delegate: NavDelegate?
var redView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
var navigateButton: UIButton = {
let button = UIButton(frame: CGRect(x: 200, y: 350, width: 150, height: 50))
button.setTitle("Navigate", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
button.backgroundColor = .blue
return button
}()
#objc func buttonAction(){
if self.redView.backgroundColor == .gray {
self.redView.backgroundColor = .systemPink
}
self.delegate.navigate(text:"", isShown: true)
}
override func viewDidLoad() {
navigateButton.layer.cornerRadius = 25
redView.backgroundColor = UIColor.gray
delegate.navigate(text: "Navigation Success", isShown: true)
view.addSubview(redView)
view.addSubview(navigateButton)
}
}
If you do not want to use storyboard.
let redScreenVC = RedScreenVC()
redScreenVC.delegate = self
class RedScreenVC: UIViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init() {
super.init(nibName: nil, bundle: nil)
self.initialize()
}
func initialize() {
self.view.backgroundColor=CustomColor.PAGE_BACKGROUND_COLOR_1
//From here you need to create your email and password textfield
}
}

Storyboard doesn't contain a view controller with identifier error?

I'm trying to present a programmatically made viewcontroller on a viewcontroller, where I can't figure out how to make ID of such made-up viewcontroller.
As can be seen in the code under, I have a base view controller, 'ViewController' and if I click a button(didTapButton) I want a programmatically made view controller(SecondViewController) show up.
Though I can't set the second view controller's name, that I can't even execute the code -- instantiateViewController(withIdentifier: "SecondController").
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func didTapButton(_ sender: Any) {
let controller = storyboard!.instantiateViewController(withIdentifier: "SecondController")
present(controller, animated: true)
}
}
......
class SecondViewController: UIViewController {
private var customTransitioningDelegate = TransitioningDelegate()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: "SecondController", bundle: nibBundleOrNil)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
}
How can I set up the second view controller's ID? If it's not what should be done, what else can I try?
instantiateViewController lets you instanciate something that is defined in a given storyboard. So either you name it in the storyboard via xcode or you must do something else. For example, instanciate the object from code, ie let c=SecondViewController() (with appropriate parameters). You are trying to mix different ways to instanciate an object.
You don't need any identifiers for programmatically created vcs just do
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .green
}
}
Use like
#IBAction func didTapButton(_ sender: Any) {
let vc = SecondViewController()
present(vc, animated: true)
}
Edit:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .green
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
let vc2 = SecondViewController()
vc2.providesPresentationContextTransitionStyle = true
vc2.definesPresentationContext = true
vc2.modalPresentationStyle = .overCurrentContext
self.present(vc2, animated: true)
}
}
}
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let v = UIView()
v.backgroundColor = .red
view.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
v.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
v.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
v.widthAnchor.constraint(equalToConstant:200),
v.heightAnchor.constraint(equalToConstant:200)
])
}
}

How to programmatically add uibutton action?

I have created a button and I was wondering how do I programmatically code an action for the UIButton to take me to another view controller?
This is all I have so far:
let getStartedButton: UIButton = {
let getStartedButton = UIButton()
getStartedButton.backgroundColor = UIColor(red:0.24, green:0.51, blue:0.59, alpha:1.0)
getStartedButton.setTitle("Get Started", for: .normal)
getStartedButton.titleLabel?.font = UIFont(name: "Helvetica Bold", size: 18)
getStartedButton.translatesAutoresizingMaskIntoConstraints = false
getStartedButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
return getStartedButton
}()
#objc func buttonAction(sender: UIButton!) {
print("...")
}
If you want to make the transition to another ViewController after pressing the button, you can do this in 2 ways:
1) present(_:animated:completion:)
#objc func buttonAction(sender: UIButton!) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Main") as! SecondViewController
self.present(vc, animated: true, completion: nil)
}
2) pushViewController(_:animated:)
#objc func buttonAction(sender: UIButton!) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Main") as! SecondViewController
self.navigationController?.pushViewController(vc, animated: true)
}
There are 3 ways you can show a new View Controller:
Presenting View Controller:
#objc func buttonAction(sender: UIButton!) {
let destinationVC = self.storyboard?.instantiateViewController(withIdentifier: "DestinationViewController") as! DestinationViewController
self.present(destinationVC, animated: true, completion: nil)
}
Performing a Segue from Storyboard:
If you already have the View Controller you want to present in your Storyboard, and it has a segue from your origin VC to your destination VC, then you can add an identifier to the segue and do this...
#objc func buttonAction(sender: UIButton!) {
self.performSegue(withIdentifier: "MySegueIdentifier", sender: self)
}
Pushing View Controller onto Stack (this only works if your original VC is embedded in a Navigation Controller):
#objc func buttonAction(sender: UIButton!) {
let destinationVC = self.storyboard?.instantiateViewController(withIdentifier: "DestinationViewController") as! DestinationViewController
self.navigationController?.pushViewController(destinationVC, animated: true)
}

Swift/IOS8 error: "fatal error: Can't unwrap Optional.None"

I know there are already a couple issues on this, but I can't figure it out. The previous solved issues would suggest that 'profileViewController' is nil, but I don't know why that would be the case. The UI is completely programmatic, no IB. Getting:
"fatal error: Can't unwrap Optional.None"
on pushViewController() in the following code:
class FavoritesViewController: UIViewController {
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
self.title = "Favorites"
self.tabBarItem.image = UIImage(named: "MikeIcon")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.redColor()
let profileButton = UIButton.buttonWithType(.System) as UIButton
profileButton.frame = CGRectMake(60, 300, 200, 44)
profileButton.setTitle("View Profile", forState: UIControlState.Normal)
profileButton.addTarget(self, action: "showProfile:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(profileButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showProfile(sender: UIButton) {
let profileViewController = ProfileViewController(nibName: nil, bundle: nil)
self.navigationController.pushViewController(profileViewController, animated: true)
}
Here's the relevant portion of AppDelegate.swift:
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
let feedViewController = FeedViewController(nibName: nil, bundle: nil)
let favoritesViewController = FavoritesViewController(nibName: nil, bundle: nil)
let profileViewController = ProfileViewController(nibName: nil, bundle: nil)
let tabBarController = UITabBarController()
self.window!.rootViewController = tabBarController
tabBarController.viewControllers = [feedViewController, favoritesViewController, profileViewController]
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
Is the Navigation Controller object self.navigationController nil?
The variable type on the navigationController property is an unwrapped optional. If your View Controller is not inside a UINavigationController that would be the problem.
To prevent the crash code along the following lines should be written:
if (self.navigationController)
{
self.navigationController.pushViewController(profileViewController, animated: true)
}
Alternatively you could write the code as:
self.navigationController?.pushViewController(profileViewController, animated: true)
The ? operator will prevent any further code from being executed, if self.navigationController evaluates to nil.