在Swift中防止UIViewController的多次推送主要是为了避免产生导航栈混乱、界面重叠等问题。以下是一些基础概念、相关优势、类型、应用场景以及解决方案:
可以在ViewController中设置一个标志位来判断是否已经推送过。
class MyViewController: UIViewController {
var isPushed = false
override func viewDidLoad() {
super.viewDidLoad()
// 设置按钮点击事件
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(pushAction), for: .touchUpInside)
}
@objc func pushAction() {
if !isPushed {
isPushed = true
let nextViewController = NextViewController()
navigationController?.pushViewController(nextViewController, animated: true)
}
}
}
可以通过实现UINavigationControllerDelegate协议来监听push操作。
class MyViewController: UIViewController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController == self {
// 已经在当前视图控制器,不再推送
navigationController?.delegate = nil
}
}
}
可以在push之前检查闭包的返回值,如果已经推送过则不再推送。
class MyViewController: UIViewController {
var pushCompletionHandler: ((Bool) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(pushAction), for: .touchUpInside)
}
@objc func pushAction() {
if pushCompletionHandler == nil {
pushCompletionHandler = { [weak self] (isPushed) in
if isPushed {
let nextViewController = NextViewController()
self?.navigationController?.pushViewController(nextViewController, animated: true)
}
}
pushCompletionHandler?(true)
}
}
}
通过以上方法,可以有效防止UIViewController的多次推送,提升应用的稳定性和用户体验。
领取专属 10元无门槛券
手把手带您无忧上云