1

I want to remove back-button which takes me to previous VC. Is solution in changing rootVC or?
I have LoginVC and HomeVC. If user successfully logs in, he shouldn't have an option to go back to login screen because it makes no sense.

LoginVC:

let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let homeVC = (mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController)
self.navigationController?.pushViewController(homeVC , animated: true)

I think it is about changing rootVC, not this(as I found on Stackoverflow):

self.navigationItem.rightBarButtonItem.hidden = YES

Mohit Kumar
  • 2,898
  • 3
  • 21
  • 34
faris97
  • 402
  • 4
  • 24
  • You can change rootViewController on a successful login that could be a solution for your back problem after a successful login. If you want I can provide some code. – Mohit Kumar Jan 29 '20 at 16:01
  • Hmm, if it is not a problem, post it. I have already tried something but it didn't work... – faris97 Jan 29 '20 at 16:04
  • Please check the answer. If that solves your problem – Mohit Kumar Jan 29 '20 at 16:09
  • Does this answer your question? [Swift - How to hide back button in navigation item?](https://stackoverflow.com/questions/27373812/swift-how-to-hide-back-button-in-navigation-item) – Faysal Ahmed Jan 29 '20 at 16:46
  • Man, read again my last 2 sentences in question – faris97 Jan 29 '20 at 16:47

5 Answers5

2

Rather than mess around with swapping the app's .rootViewController, you can set the navigation controller's viewController stack:

let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let homeVC = (mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController)

// instead of pushing to homeVC
//self.navigationController?.pushViewController(homeVC , animated: true)

// set homeVC as the only VC in the navigation stack
self.navigationController?.setViewControllers([homeVC], animated: true)

You can also use that when you allow your user to log-out (just replace homeVC with your startup VC).

Here is some simple example code:

class StartViewController: UIViewController {

    // has a button in Storyboard to push to LogInViewController

}

class LogInViewController: UIViewController {

    @IBAction func doLoginTapped(_ sender: Any) {
        if let vc = storyboard?.instantiateViewController(withIdentifier: "HomeVC") as? HomeViewController {
            self.navigationController?.setViewControllers([vc], animated: true)
        }
    }

}

class HomeViewController: UIViewController {

    // has a button in Storyboard to push to LoggedInSecondViewController

    @IBAction func doLogoutTapped(_ sender: Any) {
        if let vc = storyboard?.instantiateViewController(withIdentifier: "StartVC") as? StartViewController {
            self.navigationController?.setViewControllers([vc], animated: true)
        }
    }

}

class LoggedInSecondViewController: UIViewController {

}

and here is the Storyboard for that code:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="EqK-Mj-3Vf">
    <device id="retina4_7" orientation="portrait" appearance="light"/>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--Log In View Controller-->
        <scene sceneID="e5u-QJ-Bww">
            <objects>
                <viewController id="b3W-0i-Mlb" customClass="LogInViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="ncx-cU-8Af">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="OSX-B9-w8Z">
                                <rect key="frame" x="154.5" y="318.5" width="66" height="30"/>
                                <state key="normal" title="Do Log In"/>
                                <connections>
                                    <action selector="doLoginTapped:" destination="b3W-0i-Mlb" eventType="touchUpInside" id="j1a-uJ-1IG"/>
                                </connections>
                            </button>
                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="This is LogIn VC" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="NsK-V0-VeG">
                                <rect key="frame" x="126" y="121" width="123" height="21"/>
                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                <nil key="textColor"/>
                                <nil key="highlightedColor"/>
                            </label>
                        </subviews>
                        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                        <constraints>
                            <constraint firstItem="NsK-V0-VeG" firstAttribute="centerX" secondItem="ncx-cU-8Af" secondAttribute="centerX" id="QpB-r9-5qU"/>
                            <constraint firstItem="NsK-V0-VeG" firstAttribute="top" secondItem="EbT-Jq-J3U" secondAttribute="top" constant="77" id="ZKY-xE-pEb"/>
                            <constraint firstItem="OSX-B9-w8Z" firstAttribute="centerX" secondItem="ncx-cU-8Af" secondAttribute="centerX" id="fMq-4v-XyT"/>
                            <constraint firstItem="OSX-B9-w8Z" firstAttribute="centerY" secondItem="ncx-cU-8Af" secondAttribute="centerY" id="qVY-nC-PqE"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="EbT-Jq-J3U"/>
                    </view>
                    <navigationItem key="navigationItem" id="o8k-0O-cNJ"/>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="uP4-Vf-4SL" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="380" y="824"/>
        </scene>
        <!--Start View Controller-->
        <scene sceneID="SdS-pG-Q2l">
            <objects>
                <viewController storyboardIdentifier="StartVC" id="cLV-i6-MSZ" customClass="StartViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="Dy4-oJ-DW4">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="IP4-Qz-zns">
                                <rect key="frame" x="107" y="318.5" width="161" height="30"/>
                                <state key="normal" title="Push to go to Log In VC"/>
                                <connections>
                                    <segue destination="b3W-0i-Mlb" kind="show" id="MFe-2F-dT0"/>
                                </connections>
                            </button>
                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="This is Start VC" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="IFb-C0-mX9">
                                <rect key="frame" x="128.5" y="133" width="118" height="21"/>
                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                <nil key="textColor"/>
                                <nil key="highlightedColor"/>
                            </label>
                        </subviews>
                        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                        <constraints>
                            <constraint firstItem="IP4-Qz-zns" firstAttribute="centerX" secondItem="Dy4-oJ-DW4" secondAttribute="centerX" id="0df-jh-VtW"/>
                            <constraint firstItem="IFb-C0-mX9" firstAttribute="top" secondItem="FgR-v5-onA" secondAttribute="top" constant="89" id="0wq-KY-OwB"/>
                            <constraint firstItem="IFb-C0-mX9" firstAttribute="centerX" secondItem="Dy4-oJ-DW4" secondAttribute="centerX" id="AbM-cV-Fih"/>
                            <constraint firstItem="IP4-Qz-zns" firstAttribute="centerY" secondItem="Dy4-oJ-DW4" secondAttribute="centerY" id="OZz-KS-otd"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="FgR-v5-onA"/>
                    </view>
                    <navigationItem key="navigationItem" id="FZs-4c-uJy"/>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="ZsD-zq-DWe" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-423" y="825"/>
        </scene>
        <!--Navigation Controller-->
        <scene sceneID="eYF-Ds-vCn">
            <objects>
                <navigationController automaticallyAdjustsScrollViewInsets="NO" id="EqK-Mj-3Vf" sceneMemberID="viewController">
                    <toolbarItems/>
                    <navigationBar key="navigationBar" contentMode="scaleToFill" insetsLayoutMarginsFromSafeArea="NO" id="fyf-nl-MqT">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
                        <autoresizingMask key="autoresizingMask"/>
                    </navigationBar>
                    <nil name="viewControllers"/>
                    <connections>
                        <segue destination="cLV-i6-MSZ" kind="relationship" relationship="rootViewController" id="4nw-Xk-KCB"/>
                    </connections>
                </navigationController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="QOw-4S-yYe" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-1188" y="825"/>
        </scene>
        <!--Logged In Second View Controller-->
        <scene sceneID="vaS-nn-D30">
            <objects>
                <viewController id="cgP-NN-DdJ" customClass="LoggedInSecondViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="phV-Lb-f4V">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="647"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="This is Second Logged-In VC" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="plS-RQ-TJc">
                                <rect key="frame" x="76.5" y="313" width="222.5" height="21"/>
                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                <nil key="textColor"/>
                                <nil key="highlightedColor"/>
                            </label>
                        </subviews>
                        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                        <constraints>
                            <constraint firstItem="plS-RQ-TJc" firstAttribute="centerY" secondItem="phV-Lb-f4V" secondAttribute="centerY" id="1l4-Gm-4xX"/>
                            <constraint firstItem="plS-RQ-TJc" firstAttribute="centerX" secondItem="phV-Lb-f4V" secondAttribute="centerX" id="lgM-6G-ddH"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="I3a-uq-iVv"/>
                    </view>
                    <navigationItem key="navigationItem" id="ZiS-qO-6ai"/>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="2aj-tp-f02" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="380" y="1493"/>
        </scene>
        <!--Home View Controller-->
        <scene sceneID="aDs-4i-uOT">
            <objects>
                <viewController storyboardIdentifier="HomeVC" id="2Sw-P5-7xX" customClass="HomeViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="GGR-T3-B1f">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="This is Home VC" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="9r1-tN-d64">
                                <rect key="frame" x="124.5" y="323" width="126" height="21"/>
                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                <nil key="textColor"/>
                                <nil key="highlightedColor"/>
                            </label>
                            <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="IgB-1W-AgB">
                                <rect key="frame" x="133.5" y="126" width="108" height="30"/>
                                <state key="normal" title="Push to Second"/>
                                <connections>
                                    <segue destination="cgP-NN-DdJ" kind="show" id="xQa-nT-FSl"/>
                                </connections>
                            </button>
                            <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="VXN-mx-1xi">
                                <rect key="frame" x="148.5" y="206" width="78" height="30"/>
                                <state key="normal" title="Do Log Out"/>
                                <connections>
                                    <action selector="doLogoutTapped:" destination="2Sw-P5-7xX" eventType="touchUpInside" id="QER-XU-zLa"/>
                                </connections>
                            </button>
                        </subviews>
                        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                        <constraints>
                            <constraint firstItem="IgB-1W-AgB" firstAttribute="centerX" secondItem="GGR-T3-B1f" secondAttribute="centerX" id="Nel-cp-Vpn"/>
                            <constraint firstItem="9r1-tN-d64" firstAttribute="centerY" secondItem="GGR-T3-B1f" secondAttribute="centerY" id="XHH-fK-URc"/>
                            <constraint firstItem="VXN-mx-1xi" firstAttribute="top" secondItem="IgB-1W-AgB" secondAttribute="bottom" constant="50" id="eun-AA-w1O"/>
                            <constraint firstItem="9r1-tN-d64" firstAttribute="centerX" secondItem="GGR-T3-B1f" secondAttribute="centerX" id="n35-L7-XkI"/>
                            <constraint firstItem="VXN-mx-1xi" firstAttribute="centerX" secondItem="GGR-T3-B1f" secondAttribute="centerX" id="p2K-Ol-BjT"/>
                            <constraint firstItem="IgB-1W-AgB" firstAttribute="top" secondItem="r8E-HZ-gYH" secondAttribute="top" constant="126" id="z1y-oX-tvc"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="r8E-HZ-gYH"/>
                    </view>
                    <navigationItem key="navigationItem" id="EUX-Nq-hb0"/>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="nmk-R4-zEt" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-423" y="1493"/>
        </scene>
    </scenes>
</document>
DonMag
  • 69,424
  • 5
  • 50
  • 86
  • After a ton of complicated codes, here comes the simplest one that works. Thanks mate! – faris97 Jan 29 '20 at 17:00
  • I mean it was the simplest before you added these 2 another long code sectios. :) – faris97 Jan 29 '20 at 17:07
  • 1
    @faris97 - heh heh... the code is still really short and simple. The big section is the source for an example storyboard (which is just here for convenience) -- but, since you included a smiley-face, I'm sure you understood that :) – DonMag Jan 29 '20 at 17:11
0

The example is with ViewController...you can change it to your TabViewController or Simply Navigation View Controller.

let _APP_DELEGATE = UIApplication.shared.delegate as! AppDelegate

let homeVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

_APP_DELEGATE.window = UIWindow(frame: UIScreen.main.bounds)
_APP_DELEGATE.window?.rootViewController = homeVC
_APP_DELEGATE.window?.makeKeyAndVisible()
Mohit Kumar
  • 2,898
  • 3
  • 21
  • 34
0

Just pop the login VC and push the homevc:

// Method in LoginViewController.swift
func didLogin() {
  if let navigationController = navigationController {
    navigationController.popViewController(animated: false)
    navigationController.pushViewController(homeVC, animated: false)
  }
}

The reason for the if let statement is that the login VC won't have a navigation controller once it's been popped, so you need to keep a reference to it in order to do the subsequent push.

Rudedog
  • 4,323
  • 1
  • 23
  • 34
0

set directly to rootViewController

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = YourViewController

or in IOS 13 Scene delegate

let scene = UIApplication.shared.connectedScenes.first
        if let getSceneDelegate : SceneDelegate = (scene?.delegate as? SceneDelegate) {
            getSceneDelegate.window?.rootViewController = YourController
        }
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
0

You can set root view controller as your that screen which comes after logingin.