如何将用户从非UIView类推送到ViewController



我想知道如何将用户从常规 swift 类推回特定的 ViewController 而不具有非 UIView 类

class nonUI {
function Push() {
//How to send user back to specific VC here?
}
}

这是一个通用方法,如果需要,您可以在类内或类外用于推送,否则如果视图控制器的实例在堆栈中,它将弹出:

func pushIfRequired(className:AnyClass) {
if (UIViewController.self != className) {
print("Your pushed class must be child of UIViewController")
return
}
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var isPopDone = false
let mainNavigation = UIApplication.shared.delegate?.window??.rootViewController as? UINavigationController
let viewControllers = mainNavigation!.viewControllers
for vc in viewControllers {
if (type(of: vc) == className) {
mainNavigation?.popToViewController(vc, animated: true)
isPopDone =  true
break
}
}
if isPopDone == false{
let instanceSignUp = storyboard.instantiateViewController(withIdentifier: NSStringFromClass(className)) // Identifier must be same name as class
mainNavigation?.pushViewController(instanceSignUp, animated: true)
}
}

使用

pushIfRequired(className: SignupVC.self)

您还可以利用NotificationCenter来实现"请求视图控制器"的松散耦合方式; 如果你愿意的话。

例如,创建一个自定义UINavigationController来观察自定义通知,并在收到通知后查找请求的UIViewController并弹出回该通知。

class MyNavigationController : UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forName: NSNotification.Name("RequestViewController"), object: nil, queue: OperationQueue.main) { [unowned self] (note) in
guard let targetType = note.object as? UIViewController.Type else {
print("Please provide the type of the VC to display as an `object` for the notification")
return
}
// Find the first VC of the requested type
if let targetVC = self.viewControllers.first(where: { $0.isMember(of: targetType) }) {
self.popToViewController(targetVC, animated: true)
}
else {
// do what needs to be done? Maybe instantiate a new object and push it?
}
}
}
}

然后在要返回到特定视图控制器的对象中,发布通知。

@IBAction func showViewController(_ sender: Any) {
NotificationCenter.default.post(Notification(name: NSNotification.Name("RequestViewController"), object: ViewController2.self))
}

现在,将此方法用于其他演示样式也相当容易。 除了使用通知中心,您还可以召集调解员来实现松散耦合。

你不能。UIViewController及其子类只能处理屏幕之间的导航。

在您的情况下,需要将链接(变量(传递给自定义类中的导航控制器。

喜欢:

class nonUI {
var navigationController: UINavigationController?
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
function Push() {
//How to send user back to specific VC here?
navigationController?.popViewController(animated: true)
}
}

最新更新