Подтвердить что ты не робот

Переопределяющий метод с селектором 'touchhesBegan: withEvent:' имеет несовместимый тип '(NSSet, UIEvent) ->()'

Xcode 6.3. Внутри класса, реализующего протокол UITextFieldDelegate, я хотел бы переопределить метод touchhesBegan(), чтобы скрыть клавиатуру. Если я избегаю ошибки компилятора в spec функции, то возникает ошибка с интегратором, пытающаяся прочитать "касание" из набора или NSSet, иначе super.touchesBegan(касается, 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)
    }

Try:

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

Ошибка компилятора: Переопределяющий метод с селектором 'touchhesBegan: withEvent:' имеет несовместимый тип '(NSSet, UIEvent) → ()' и

super.touchesBegan(touches , withEvent:event)

также жалуется

'NSSet' неявно конвертируется в 'Set'; вы хотели использовать 'as' для явного преобразования?

Try:

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

Ошибка компилятора:  Тип "AnyObject" не соответствует протоколу "Hashable"

Try:

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

Ошибка компилятора в

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

'Set' не имеет члена с именем 'anyObject', но функция spec и вызов super() в порядке!

Try:

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

Ошибка компилятора: Невозможно специализировать нестандартный тип "NSSet"

4b9b3361

Ответ 1

Swift 1.2 (Xcode 6.3) представил собственный тип Set, который соединяет мосты с NSSet. Это упоминается в блоге Swift и в Xcode 6.3 примечания к выпуску, , но, по-видимому, еще не добавлены в официальную документацию (обновление: As Ахмад Гадири отметил, это задокументировано сейчас).

Теперь метод 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): (Сравнить Переопределение ошибки func в Swift 2)

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)
}

Ответ 2

С помощью xCode 7 и swift 2.0 используйте следующий код:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if let touch =  touches.first{
        print("\(touch)")
    }
    super.touchesBegan(touches, withEvent: event)
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if let touch = touches.first{
        print("\(touch)")
    }
    super.touchesEnded(touches, withEvent: event)
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if let touch = touches.first{
        print("\(touch)")
    }
    super.touchesMoved(touches, withEvent: event)
}

Ответ 3

Теперь он находится в справочнике Apple API и для переопределения в xCode версии 6.3 и swift 1.2 вы можете использовать этот код:

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

Ответ 4

Использование Swift 3 и Xcode 8

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

}

override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
// Don't forget to add "?" after Set<UITouch>
}

Ответ 5

Текущая версия сейчас для новейшего обновления с xCode 7.2 Swift 2.1 от 19 декабря 2015 года.

В следующий раз, когда вы снова получите такую ​​ошибку, удалите эту функцию и начните вводить ее снова "touchhesBe...", а xCode должен автоматически завершить ее до самой новой для вас, вместо того, чтобы пытаться исправить старую.

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch: AnyObject! in touches {
        let touchLocation = touch.locationInNode(self)

        //Use touchLocation for example: button.containsPoint(touchLocation) meaning the user has pressed the button.
    }
}

Ответ 6

Что для меня работало:

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

        super.touchesBegan(touches , withEvent:event!)
    }

Ответ 7

Небольшое дополнение. Для быстрой компиляции без ошибки вам нужно добавить

import UIKit.UIGestureRecognizerSubclass