小编典典

使用选择器'touchesBegan:withEvent:'的重写方法具有不兼容的类型'(NSSet,UIEvent)->()'

swift

Xcode
6.3。在实现UITextFieldDelegate协议的类中,我想重写touchesBegan()方法以可能隐藏键盘。如果我避免函数规范中的编译器错误,则尝试从Set或NSSet读取“
touch”时会出现编译器错误,否则super.touchesBegan(touches,withEvent:event)会引发错误。这些组合之一是在Xcode
6.2中编译的!(因此,Swift“ Set”的文档在哪里以及如何从其中获取元素?)

 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { 
    // Hiding the Keyboard when the User Taps the Background
        if let touch =  touches.anyObject() as? UITouch {
            if nameTF.isFirstResponder() && touch.view != nameTF {
                nameTF.resignFirstResponder();
            }
        }
        super.touchesBegan(touches , withEvent:event)
    }

尝试:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) or
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent)

编译器错误:具有选择器’touchesBegan:withEvent:’的重写方法具有不兼容的类型’(NSSet,UIEvent)->()’,并且

super.touchesBegan(touches , withEvent:event)

也抱怨

“ NSSet”不能隐式转换为“ Set”;您是说要使用“ as”进行显式转换吗?

尝试:

override func touchesBegan(touches: Set<AnyObject>, withEvent event: UIEvent)

编译器错误:类型“ AnyObject”不符合协议“哈希”

尝试:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)

编译器错误

if let touch = touches.anyObject() as? UITouch

‘Set’没有名为’anyObject’的成员,但函数规范和对super()的调用都可以!

尝试:

override func touchesBegan(touches: NSSet<AnyObject>, withEvent event: UIEvent) -> () or
override func touchesBegan(touches: NSSet<NSObject>, withEvent event: UIEvent)

编译器错误:无法专用于非通用类型“ NSSet”


阅读 260

收藏
2020-07-07

共1个答案

小编典典

Swift 1.2(Xcode 6.3)
引入了Set与桥接的本机类型NSSetSwift博客Xcode6.3发行说明中都提到了这一点, 但显然尚未将其添加到官方文档中
(更新:正如Ahmad Ghadiri所指出的,现在
记录在案)。

UIResponder方法现在声明为

func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)

您可以像这样覆盖它:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
        // ...
    }
    super.touchesBegan(touches , withEvent:event)
}

Swift 2(Xcode 7)更新:( 比较Swift 2中的OverrideFunc错误]

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        // ...
    }
    super.touchesBegan(touches, withEvent:event)
}

Swift 3更新:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        // ...
    }
    super.touchesBegan(touches, with: event)
}
2020-07-07