How to resign first responder from text field when user tap elsewhere?

前端 未结 18 3096
野趣味
野趣味 2020-12-14 02:12

I have filled my view with ScrollView (same size as the view) and I\'m stuck at how to resign first responder when user tap elsewhere in the View (or the scrollview). Any id

18条回答
  •  攒了一身酷
    2020-12-14 02:39

    Create your IBOutlet in ViewController.h file like below:

    //YOUR ViewController.h FILE
    
    #import 
    
    @interface ViewController : UIViewController
    {
        //WIRE THIS WITH YOUR UITextField OBJECT AT YOUR .xib FILE
        IBOutlet UITextField *yourIBOutletUITextField;
    }
    
    @end
    

    Add this to your ViewController.m file:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
         [yourIBOutletUITextField resignFirstResponder];
    }
    

    like below:

    //YOUR ViewController.m FILE
    
    #import "ViewController.h"
    
    @implementation ViewController
    
    
    //ADD THIS METHOD BELOW
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
         [yourIBOutletUITextField resignFirstResponder];
    }
    
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Release any cached data, images, etc that aren't in use.
    }
    
    #pragma mark - View lifecycle
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        }
    
    - (void)viewDidUnload
    {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
    }
    
    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    }
    
    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
    }
    
    - (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
    }
    
    - (void)viewDidDisappear:(BOOL)animated
    {
        [super viewDidDisappear:animated];
    }
    
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        // Return YES for supported orientations
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    }
    
    @end
    

提交回复
热议问题