David Thomlinson David Thomlinson - 3 months ago 10
Swift Question

Swift method doesn't override any method from its superclass

I am relatively new to Swift and I am following some basic tutorials but I seem to be having a problem with some methods which attempt to allow the user to press return to minimise the keyboard or to click off the keyboard and the keyboard will disappear, I understand why I am receiving these errors but have no clue how to go about fixing it, I feel something may have been changed in the newer version of Swift I am using as he is using an older version than me, could anyone possibly explain how to go about fixing these two errors please? Any help would be greatly appreciated here is my source code: (First error, value of type 'viewController' has no member 'text' and secondly, touchesBegan method does not override any method from its superclass)

import UIKit

class ViewController: UIViewController {

@IBAction func buttonPressed(sender: AnyObject) {

label.text = textArea.text

}

@IBOutlet weak var textArea: UITextField!

@IBOutlet weak var label: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

self.text.delegate = self

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}

func textFieldShouldReturn(textField: UITextField!) -> Bool {

textField.resignFirstResponder()

return true

}

}

Answer

You have 2 problems here, based on the images you posted:

1) The method touhesBegan you are using is not correct:

Correct one:

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

Yours:

func touchesBegan(touches: NSSet, withEvent event: UIEvent)

I think you want a delegate for the UITextField, so this one is not corerct: touchesBegan is a method for the UIReponder delegate and not for UITextFieldDelegate.

Here you can find the reference for the UITextFieldDelegate.

2) the variable text doesn't exists in your code. I think you wanted to use textArea instead.

Hope this can help you, happy coding!

Comments