【问题标题】:Swift navigation bar - remove left bar itemSwift 导航栏 - 删除左侧栏项目
【发布时间】:2020-05-15 04:11:15
【问题描述】:

我想删除将我带到上一个 VC 的后退按钮。是改变rootVC还是解决方案?
我有 LoginVC 和 HomeVC。如果用户成功登录,他不应该有返回登录屏幕的选项,因为这没有任何意义。

登录VC:

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

我认为这是关于更改 rootVC,而不是这个(正如我在 Stackoverflow 上发现的):

self.navigationItem.rightBarButtonItem.hidden = YES

【问题讨论】:

  • 您可以在成功登录时更改 rootViewController,这可能是成功登录后您的背部问题的解决方案。如果你愿意,我可以提供一些代码。
  • 嗯,没问题的话,贴吧。我已经尝试了一些东西,但它没有用......
  • 请检查答案。如果这能解决您的问题
  • 伙计,再读一遍我的最后两句话

标签: ios swift uinavigationbar uinavigationitem rootviewcontroller


【解决方案1】:

示例是 ViewController...您可以将其更改为 TabViewController 或 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()

【讨论】:

  • 它给了我一个 SigaBrt 信号,消息:无法将“App.HomeViewController”类型的值转换为“UINavigationController”
  • SigaBrt 是什么意思?
  • 代码已更新。请检查
  • HomeVC 是。打开,但屏幕上仍然有 LoginVC。这怎么可能哈哈我知道 HomeVC 已打开,因为它会在 viewDidLoad 中打印应该打印的内容?
  • 可以分享截图吗?并使用代码位置更新代码
【解决方案2】:

只需弹出登录VC并推送homevc:

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

if let声明的原因是登录VC一旦弹出就没有导航控制器,所以你需要保留对它的引用才能进行后续推送。

【讨论】:

  • 一切都和以前一样..没有帮助
【解决方案3】:

直接设置为rootViewController

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

或在 IOS 13 场景委托中

let scene = UIApplication.shared.connectedScenes.first
        if let getSceneDelegate : SceneDelegate = (scene?.delegate as? SceneDelegate) {
            getSceneDelegate.window?.rootViewController = YourController
        }

【讨论】:

    【解决方案4】:

    您可以设置导航控制器的 viewController 堆栈,而不是随意更换应用的 .rootViewController

    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)
    

    您也可以在允许用户注销时使用它(只需将 homeVC 替换为您的启动 VC)。

    下面是一些简单的示例代码:

    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 {
    
    }
    

    这是该代码的情节提要:

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

    【讨论】:

    • 在一堆复杂的代码之后,这里出现了最简单的代码。谢谢老哥!
    • 我的意思是在你添加这两个另一个长代码部分之前这是最简单的。 :)
    • @faris97 - 嘿嘿......代码仍然非常简短。大部分是示例故事板的来源(只是为了方便起见在这里)-但是,由于您包含笑脸,我相信您理解:)
    【解决方案5】:

    您可以将根视图控制器设置为登录后出现的屏幕。

    【讨论】: