Nice programing

탐색 스택에서 뷰 컨트롤러 제거

nicepro 2020. 9. 25. 23:37
반응형

탐색 스택에서 뷰 컨트롤러 제거


5 개의 UIViewController가있는 탐색 스택이 있습니다. 다섯 번째 뷰 컨트롤러에서 버튼을 클릭하여 스택에서 세 번째 및 네 번째 뷰 컨트롤러를 제거하고 싶습니다. 이것이 가능합니까? 그렇다면 어떻게?


이 코드를 사용하고 즐기십시오.

NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];

// [navigationArray removeAllObjects];    // This is just for remove all view controller from navigation stack.
[navigationArray removeObjectAtIndex: 2];  // You can pass your index here
self.navigationController.viewControllers = navigationArray;
[navigationArray release];

이것이 당신을 도울 것입니다.

편집 : 스위프트 코드

guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
navigationArray.remove(at: navigationArray.count - 2) // To remove previous UIViewController
self.navigationController?.viewControllers = navigationArray

먼저 배열의 모든 뷰 컨트롤러를 가져온 다음 해당 뷰 컨트롤러 클래스를 확인한 후 원하는 컨트롤러를 삭제할 수 있습니다.

다음은 작은 코드입니다.

NSArray* tempVCA = [self.navigationController viewControllers];

for(UIViewController *tempVC in tempVCA)
{
    if([tempVC isKindOfClass:[urViewControllerClass class]])
    {
        [tempVC removeFromParentViewController];
    }
}

나는 이것이 당신의 일을 더 쉽게 만들 것이라고 생각합니다.


Swift 3 및 4/5

self.navigationController!.viewControllers.removeAll()

self.navigationController?.viewControllers.remove(at: "insert here a number")

스위프트 2.1

모두 제거:

self.navigationController!.viewControllers.removeAll()

색인에서 제거

self.navigationController?.viewControllers.removeAtIndex("insert here a number")

removeFirst, range 등과 같은 더 많은 가능한 작업이 있습니다.


스위프트 2.0 :

  var navArray:Array = (self.navigationController?.viewControllers)!
  navArray.removeAtIndex(navArray.count-2)
  self.navigationController?.viewControllers = navArray

스위프트 5 :

        navigationController?.viewControllers.removeAll(where: { (vc) -> Bool in
            if vc.isKind(of: MyViewController.self) || vc.isKind(of: MyViewController2.self) {
                return false
            }
            else {
                return true
            }
        })

setViewControllersfrom 함수를 사용 UINavigationController하는 것이 가장 좋은 방법입니다. animated애니메이션을 활성화하는 매개 변수 도 있습니다 .

func setViewControllers(_ viewControllers: [UIViewController], animated: Bool)

질문에 대한 신속한 예

func goToFifthVC() {

    var currentVCStack = self.navigationController?.viewControllers
    currentVCStack?.removeSubrange(2...3)

    let fifthVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "fifthVC")
    currentVCStack?.append(fifthVC)

    self.navigationController?.setViewControllers(currentVCStack!, animated: true)
}

I tried other ways like [tempVC removeFromParentViewController];. It make weird behaviour, removed ViewController navigation still showing when pop back like reported by @robin-ellerkmann


If you are trying to move to 2nd view controller from 5th view controller (skipping 3rd and 4th), you would like to use [self.navigationController popToviewController:secondViewController].

You can obtain the secondViewController from the navigation controller stack.

secondViewController =  [self.navigationController.viewControllers objectAtIndex:yourViewControllerIndex];

Use this

if let navVCsCount = navigationController?.viewControllers.count {
    navigationController?.viewControllers.removeSubrange(Range(2..<navVCsCount - 1))
}

It will take care of ViewControllers of navigationController. viewControllers and also a navigationItems stacked in navigationBar.

Note: Be sure to call it at least after viewDidAppear


This solution worked for me in swift 4:

let VCCount = self.navigationController!.viewControllers.count
self.navigationController?.viewControllers.removeSubrange(Range(VCCount-3..<VCCount - 1))

your current view controller index in stack is:

self.navigationController!.viewControllers.count - 1

Swift 5, Xcode 10.2

I found this approach simple by specifying which view controller(s) you want to remove from the navigation stack.

extension UINavigationController {

func removeViewController(_ controller: UIViewController.Type) {
    if let viewController = viewControllers.first(where: { $0.isKind(of: controller.self) }) {
        viewController.removeFromParent()
    }
}

}

Example use:

navigationController.removeViewController(YourViewController.self)

Swift 5.1, Xcode 11

extension UINavigationController{
public func removePreviousController(total: Int){
    let totalViewControllers = self.viewControllers.count
    self.viewControllers.removeSubrange(totalViewControllers-total..<totalViewControllers - 1)
}}

Make sure to call this utility function after viewDidDisappear() of previous controller or viewDidAppear() of new controller


I wrote an extension with method which removes all controllers between root and top, unless specified otherwise.

extension UINavigationController {
func removeControllers(between start: UIViewController?, end: UIViewController?) {
    guard viewControllers.count > 1 else { return }
    let startIndex: Int
    if let start = start {
        guard let index = viewControllers.index(of: start) else {
            return
        }
        startIndex = index
    } else {
        startIndex = 0
    }

    let endIndex: Int
    if let end = end {
        guard let index = viewControllers.index(of: end) else {
            return
        }
        endIndex = index
    } else {
        endIndex = viewControllers.count - 1
    }
    let range = startIndex + 1 ..< endIndex
    viewControllers.removeSubrange(range)
}

}

If you want to use range (for example: 2 to 5) you can just use

    let range = 2 ..< 5
    viewControllers.removeSubrange(range)

Tested on iOS 12.2, Swift 5

참고URL : https://stackoverflow.com/questions/10281545/removing-viewcontrollers-from-navigation-stack

반응형