Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

motionEnded method in Swift 2.0

I can't seem to get the motion detection methods to work with Swift 2.0/Xcode 7. The error I'm getting indicates: 'Method does not override any method from its superclass'. I want to detect various motions using the built in UIEvent methods.. i.e. shake. Here's what I have inside the class

    //this is used for detecting UIEvents i.e. 'Shake'
    override func canBecomeFirstResponder() -> Bool {
    return true
    }

....

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent)
    {
        if motion == .MotionShake && randomNumber == SHAKE
        {
            print("SHAKE RECEIVED")
            correctActionPerformed = true
        }
        else if motion == .MotionShake && randomNumber != SHAKE
        {
            print("WRONG ACTION")
            wrongActionPerformed = true
        }
         else
        {
            print("WRONG ACTION")
            wrongActionPerformed = true
        }
    }

The same problem was encountered here: Swift 2 migration problems

like image 717
Ryan Lake Avatar asked Jun 03 '26 17:06

Ryan Lake


2 Answers

The issue here is that the parameters have been updated in Swift 2.0. The UIEvent parameter is now UIEvent?. To avoid these issues in the future if you know the function to be overridden just start typing in "override func " and Xcode's autocomplete should give you the desired function.

like image 70
coe720 Avatar answered Jun 05 '26 07:06

coe720


Just wanted to add the same in Swift 3 iOS 10:

override var canBecomeFirstResponder: Bool {
    return true
}

override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
    if motion == .motionShake && randomNumber == SHAKE
    {
        debugPrint("SHAKE RECEIVED")
        correctActionPerformed = true
    }
    else if motion == .motionShake && randomNumber != SHAKE
    {
        debugPrint("WRONG ACTION")
        wrongActionPerformed = true
    }
    else
    {
        debugPrint("WRONG ACTION")
        wrongActionPerformed = true
    }
}
like image 42
Pomo-J Avatar answered Jun 05 '26 08:06

Pomo-J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!