title: How to dismiss keyboard iOS programmatically when pressing return
body: <p>I created a <code>UITextField</code> programmatically making the <code>UITextField</code> a property of the viewController. I need to dismiss the keyboard with the return and the touch on the screen. I was able to get the screen touch to dismiss, but pressing return is not working.</p>
  <p>I've seen how to do it with storyboards and by allocating and initializing the <code>UITextField</code> object directly without creating it as a property. Possible to do?</p>
  <h3>.h</h3>
  <pre><code>#import &lt;UIKit/UIKit.h&gt;
  
  @interface ViewController : UIViewController &lt;UITextFieldDelegate&gt;
  
  @property (strong, atomic) UITextField *username;
  
  @end
  </code></pre>
  <h3>.m</h3>
  <pre><code>#import &quot;ViewController.h&quot;
  
  @interface ViewController ()
  
  @end
  
  @implementation ViewController
  
  - (void)viewDidLoad
  {
      [super viewDidLoad];
      
      // Do any additional setup after loading the view, typically from a nib.
      
      self.view.backgroundColor = [UIColor blueColor];
      self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
      self.username.placeholder = @&quot;Enter your username&quot;;
      self.username.backgroundColor = [UIColor whiteColor];
      self.username.borderStyle = UITextBorderStyleRoundedRect;
      if (self.username.placeholder != nil) {
          self.username.clearsOnBeginEditing = NO;
      }
      _username.delegate = self; 
      
      [self.view addSubview:self.username];
      [_username resignFirstResponder];
      
  }
  
  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
      NSLog(@&quot;touchesBegan:withEvent:&quot;);
      [self.view endEditing:YES];
      [super touchesBegan:touches withEvent:event];
  }
  
  @end
  </code></pre>