Search code examples
iosswiftuinavigationbaruinavigationitemrootviewcontroller

Swift navigation bar - remove left bar item


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


Solution

  • 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>