gpt4 book ai didi

swift - 如何在 Swift 中使用 contains() 检查 self ?

转载 作者:可可西里 更新时间:2023-11-01 01:06:02 25 4
gpt4 key购买 nike

我正在尝试检查我的 View Controller 上的后退按钮是否被按下,但我很难在 Swift 中检测到这一点。

使用这段代码:

    if (contains(self.navigationController?.viewControllers, self)) {
println("Back button not pressed")
} else {
self.updateSearchQueryModel()
}

我收到错误:

Could not find an overload for contains that accepts the supplied arguments.

我确实以另一种方式得到了我想要的结果,但我仍然对为什么会发生此错误感到困惑。

为什么会这样?我可以不检查 self 是否存在于数组中吗?

我无法转换为 Swift 的 Objective C 原始代码源: Setting action for back button in navigation controller

-(void) viewWillDisappear:(BOOL)animated {
if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
// back button was pressed. We know this is true because self is no longer
// in the navigation stack.
}
[super viewWillDisappear:animated];
}

请不要告诉我如何检测后退按钮是否被按下。我已经在这里找到了。

目标解决方案来源:Detecting when the 'back' button is pressed on a navbar

最佳答案

如果您查看 viewControllers 属性的声明,您会注意到它是 [AnyObject]! 而不是 [UIViewController]!

contains 函数要求序列元素实现 Equatable 协议(protocol),而 AnyObject 则没有。

解决方案是使用可选绑定(bind)对该数组进行显式向下转换:

if let viewControllers = self.navigationController?.viewControllers as? [UIViewController] {
if (contains(viewControllers, self)) {
println("Back button not pressed")
} else {
self.updateSearchQueryModel()
}
}

关于swift - 如何在 Swift 中使用 contains() 检查 self ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29954229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com