Programing

Swift에서 현재 뷰 컨트롤러 클래스를 어떻게 확인합니까?

lottogame 2020. 12. 3. 07:24
반응형

Swift에서 현재 뷰 컨트롤러 클래스를 어떻게 확인합니까?


내가 아는 한 이것은 Objective-C에서 작동합니다.

self.window.rootViewController.class == myViewController

현재 뷰 컨트롤러가 특정 컨트롤러인지 어떻게 확인할 수 있습니까?


Swift에서 클래스를 확인하려면 "is"를 사용 하십시오 (Swift Programming Guide의 Type Casting이라는 장의 "checking Type"에 설명 됨).

if self.window.rootViewController is MyViewController {
    //do something if it's an instance of that class
}

swift3 컴파일러를 위해 업데이트되었습니다! 그리고?

if let wd = UIApplication.shared.delegate?.window {
        var vc = wd!.rootViewController
        if(vc is UINavigationController){
            vc = (vc as! UINavigationController).visibleViewController

        }

        if(vc is LogInViewController){
            //your code
        }
    }

탐색 컨트롤러를 사용하는 경우보기 컨트롤러를 쉽게 반복 할 수 있습니다. 그런 다음 특정 인스턴스를 다음과 같이 확인할 수 있습니다.

if let viewControllers = navigationController?.viewControllers {
    for viewController in viewControllers {
        // some process
        if viewController.isKindOfClass(MenuViewController) {
            println("yes it is")
        }
    } 
}

AppDelegate에서 현재 viewController를 찾아야했습니다. 나는 이것을 사용했다

//at top of class
var window:UIWindow?

// inside my method/function
if let viewControllers = window?.rootViewController?.childViewControllers {
    for viewController in viewControllers {
        if viewController.isKindOfClass(MyViewControllerClass) {
            println("Found it!!!")
            }
        }
    }

Thapa의 대답에서 벗어나려면 사용하기 전에 viewcontroller 클래스로 캐스팅해야합니다.

   if let wd = self.view.window {
        var vc = wd.rootViewController!
        if(vc is UINavigationController){
            vc = (vc as! UINavigationController).visibleViewController
        }
        if(vc is customViewController){
            var viewController : customViewController = vc as! customViewController

이 시도

if self is MyViewController {        

}

스위프트 3

당신들에 대해서는 잘 모르겠지만이 문제로 어려움을 겪고 있습니다. 나는 다음과 같이했다.

if let window = UIApplication.shared.delegate?.window {
    if var viewController = window?.rootViewController {
        // handle navigation controllers
        if(viewController is UINavigationController){
            viewController = (viewController as! UINavigationController).visibleViewController!
        }
        print(viewController)
    }
}

I kept getting the initial view controller of my app. For some reason it wanted to stay the root view controller no matter what. So I just made a global string type variable currentViewController and set its value myself in each viewDidLoad(). All I needed was to tell which screen I was on & this works perfectly for me.


For types you can use is and if it is your own viewcontroller class then you need to use isKindOfClass like:

let vcOnTop = self.embeddedNav.viewControllers[self.embeddedNav.viewControllers.count-1]
            if vcOnTop.isKindOfClass(VcShowDirections){
                return
            }

Swift 3 | Check if a view controller is the root from within itself.

You can access window from within a view controller, you just need to use self.view.window.

Context: I need to update the position of a view and trigger an animation when the device is rotated. I only want to do this if the view controller is active.

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(
            self, 
            selector: #selector(deviceDidRotate), 
            name: .UIApplicationDidChangeStatusBarOrientation, 
            object: nil
        )
    }

    func deviceDidRotate() {
        guard let window = self.view.window else { return }

        // check if self is root view controller
        if window.rootViewController == self {
            print("vc is self")
        }

        // check if root view controller is instance of MyViewController
        if window.rootViewController is MyViewController {
            print("vc is MyViewController")
        }
    }
}

If you rotate your device while MyViewController is active, you will see the above lines print to the console. If MyViewController is not active, you will not see them.

If you're curious why I'm using UIDeviceOrientationDidChange instead of .UIDeviceOrientationDidChange, look at this answer.


let viewControllers = navController?.viewControllers
        for aViewController in viewControllers! {

            if aViewController .isKind(of: (MyClass?.classForCoder)!) {
                _ = navController?.popToViewController(aViewController, animated: true)
            }
        }

if let index = self.navigationController?.viewControllers.index(where: { $0 is MyViewController }) {
            let vc = self.navigationController?.viewControllers[vcIndex] as! MyViewController
            self.navigationController?.popToViewController(vc, animated: true)
        } else {
            self.navigationController?.popToRootViewController(animated: true)
        }

Check that way that worked better for me What is .self

if ((self.window.rootViewController?.isKind(of: WebViewController.self))!)
{
  //code
}

참고URL : https://stackoverflow.com/questions/27715861/how-do-you-check-current-view-controller-class-in-swift

반응형