当前位置:实例文章 » 其他实例» [文章]Swift 中如何判断是push 过来的页面 还是present过来的 页面

Swift 中如何判断是push 过来的页面 还是present过来的 页面

发布人:shili8 发布时间:2025-03-12 13:39 阅读次数:0

**Swift 中如何判断是 push 过来的页面还是 present 过来的页面**

在 iOS 开发中,`pushViewController:animated:` 和 `presentViewController:animated:completion:` 是两个常用的方法来跳转到新的控制器。然而,在实际开发过程中,我们经常需要区分这两种跳转方式,以便进行相应的处理和操作。

**1. 使用 unwindSegue**

首先,我们可以使用 `unwindSegue` 来实现这个功能。`unwindSegue` 是一个特殊的 segue,用于从子控制器返回到父控制器。在 iOS8 之后,这个方法变得更加方便和直观。

swift// 在父控制器中定义一个 unwindSegue@IBAction func unwindToParent(_ sender: UIStoryboardSegue) {
 // 这里可以进行相应的处理和操作}

// 然后,在子控制器中使用 unwindSegue 来跳转回父控制器override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
 if let identifier = segue.identifier {
 switch identifier {
 case "unwindSegue":
 // 这里可以进行相应的处理和操作 break default:
 break }
 }
}


**2. 使用 notification**

另一个方法是使用 `notification` 来实现这个功能。我们可以在父控制器中发送一个通知,当子控制器跳转回父控制器时,父控制器会接收到这个通知。

swift// 在父控制器中定义一个 notificationlet notificationName = Notification.Name(rawValue: "unwindSegue")

// 然后,在子控制器中使用 notification 来跳转回父控制器override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
 if let identifier = segue.identifier {
 switch identifier {
 case "pushSegue":
 // 发送一个 notification NotificationCenter.default.post(name: notificationName, object: nil)
 break default:
 break }
 }
}

// 在父控制器中接收这个 notificationoverride func viewDidLoad() {
 super.viewDidLoad()
 // 注册一个 observer NotificationCenter.default.addObserver(self, selector: #selector(unwindSegue), name: notificationName, object: nil)
}

@objc func unwindSegue(_ notification: Notification) {
 // 这里可以进行相应的处理和操作}


**3. 使用 delegate**

最后,我们可以使用 `delegate` 来实现这个功能。我们可以在父控制器中定义一个协议,子控制器会遵循这个协议,并在跳转回父控制器时调用父控制器的方法。

swift// 在父控制器中定义一个 delegate 协议protocol ParentDelegate: class {
 func didUnwindSegue()
}

class ParentViewController: UIViewController, ParentDelegate {
 // 这里可以进行相应的处理和操作 override func viewDidLoad() {
 super.viewDidLoad()
 // 注册一个 observer NotificationCenter.default.addObserver(self, selector: #selector(unwindSegue), name: notificationName, object: nil)
 }
 @objc func unwindSegue(_ notification: Notification) {
 // 这里可以进行相应的处理和操作 }
}

// 然后,在子控制器中使用 delegate 来跳转回父控制器class ChildViewController: UIViewController {
 weak var parentDelegate: ParentDelegate?
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
 if let identifier = segue.identifier {
 switch identifier {
 case "pushSegue":
 // 设置 delegate self.parentDelegate = self.parentViewController // 然后,在跳转回父控制器时调用 delegate 的方法 self.parentDelegate?.didUnwindSegue()
 break default:
 break }
 }
 }
}


**总结**

在 Swift 中,判断是 push 过来的页面还是 present 过来的页面有多种方法。使用 unwindSegue、notification 和 delegate 都可以实现这个功能。每种方法都有其优缺点和适用场景。选择合适的方法需要根据具体需求进行权衡和比较。

相关标签:ios开发语言swift
其他信息

其他资源

Top