如何从Swift中的UIView中删除所有手势识别器

时间:2014-10-05 19:39:43

标签: ios uiview swift uigesturerecognizer optional

我编写了Swift代码,尝试从给定自定义UIView类型的所有子视图中删除所有手势识别器。

let mySubviews = self.subviews.filter() {
   $0.isKindOfClass(CustomSubview)
}
for subview in mySubviews {
   for recognizer in subview.gestureRecognizers {
      subview.removeGestureRecognizer(recognizer)
   }
}

for recognizer行会产生编译错误:

'[AnyObject]?' does not have a member named 'Generator'

我尝试将for recognizer循环更改为for recognizer in enumerate(subview.gestureRecognizers),但这会产生编译错误:

Type '[AnyObject]?!' Does not conform to protocol 'SequenceType'

我看到UIView的gestureRecognizers方法返回[AnyObject]??,我认为双重包裹的返回值正在绊倒我。任何人都可以帮助我吗?

更新: 修改后的编译代码是:

if let recognizers = subview.gestureRecognizers {
   for recognizer in recognizers! {
      subview.removeGestureRecognizer(recognizer as UIGestureRecognizer)
   }
}

3 个答案:

答案 0 :(得分:92)

iOS 11更新

一般来说,通过循环遍历gestureRecognizers数组,从视图中删除所有手势识别是一个坏主意。您应该只删除添加到视图中的手势识别器,方法是跟踪您自己的实例变量中的识别器。

这在iOS 11中对于拖放所涉及的视图具有新的重要性,因为UIKit将自己的手势识别器添加到这些视图以识别拖放。

更新

您不再需要转发UIGestureRecognizer,因为UIView.gestureRecognizers已更改为在iOS 9.0中键入[UIGestureRecognizer]?

此外,通过使用nil-coalescing运算符??,您可以避免使用if语句。

for recognizer in subview.gestureRecognizers ?? [] {
    subview.removeGestureRecognizer(recognizer)
}

然而,最简单的方法是:

subview.gestureRecognizers?.forEach(subview.removeGestureRecognizer)

我们也可以在for循环中过滤子视图,如下所示:

for subview in subviews where subview is CustomSubview {
    for recognizer in subview.gestureRecognizers ?? [] {
        subview.removeGestureRecognizer(recognizer)
    }
}

或者我们可以将它们全部包装成一个表达式(为清晰起见而包裹):

subviews.lazy.filter { $0 is CustomSubview }
    .flatMap { $0.gestureRecognizers ?? [] }
    .forEach { $0.view?.removeGestureRecognizer($0) }

使用.lazy可以防止它创建不必要的临时数组。

ORIGINAL

这是关于Swift的令人讨厌的事情之一。你的for循环只能在Objective-C中工作,但在Swift中你必须显式展开可选数组:

if let recognizers = subview.gestureRecognizers {
    for recognizer in recognizers {
        subview.removeGestureRecognizer(recognizer as! UIGestureRecognizer)
    }
}

你可以强制解包它(for recognizer in subview.gestureRecognizers!),但是我不确定gestureRecognizers是否可以返回nil并且你会得到一个运行时错误 - 包裹它。

答案 1 :(得分:24)

最简单的解决方案

if (cursor != null) {
    boolean hasResult = cursor.moveToFirst();
    if (!hasResult) return false;
}

答案 2 :(得分:10)

更简单的方法是

for subview in self.subviews as [UIView] {
    if subview.isKindOfClass(CustomSubview) {
        subview.gestureRecognizers?.removeAll(keepCapacity: false)
    }
}