Function not running when return pressed

65 Views Asked by At

I have a textfield, when something is typed in the textfield and "return" on the keyboard is pressed, the keyboard should hide. But it doesn't..

Here is the code I am using:

import UIKit

class EditTableViewController: UITableViewController, UITextFieldDelegate {

var product: Product?


@IBOutlet weak var productImageView: UIImageView!
@IBOutlet weak var ProductDescriptionTextView: UITextView!
@IBOutlet weak var productTitleLabel: UITextField!



override func viewDidLoad() {
    super.viewDidLoad()
    println("loaded")
    productImageView.image = product?.image
    productTitleLabel.text = product?.title
    ProductDescriptionTextView.text = product?.description
}

override func viewWillDisappear(animated: Bool) {
    product?.title = productTitleLabel.text
    product?.description = ProductDescriptionTextView.text
    product?.image = productImageView.image!
}

 func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
{
println("return")
return true
}
}

In the console I get "loaded", but when I press return in the textfield, I don't get "return"

how come?

2

There are 2 best solutions below

0
On BEST ANSWER

You forgot to set the UITextField's delegate to your view controller (self) productTitleLabel.delegate = self - also note that you should name your variables properly to avoid confusion (productTitleTextField instead of a 'Label' suffix)

Or, instead of doing it programmatically, you can do it in storyboard by Ctrl-dragging from your textView to the view controller in storyboard, and select delegate on the popup.

first

second

Then, let your view controller conform to UITextFieldDelegate protocol:

class EditTableViewController: UITableViewController, UITextFieldDelegate {
....
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        if textField == productTitleLabel {
            textField.resignFirstResponder()
        }
        return true
    }
}
0
On

In your viewDidLoad method you have to add:

productTitleLabel.delegate = self

And update your textFieldShouldReturn like this:

func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
{
    productTitleLabel.resignFirstResponder()
    return true
}

And It will hide your keyboard when return key pressed.