觸摸非輸入區(背景)使UITextField(UISearchBar)鍵盤消失的方法

在iOS上出現軟鍵盤後,但願點擊非鍵盤部分,隱藏鍵盤,即便鍵盤消失的方法討論。 ide

第一種方法:增長一個button,相應touch down事件,隱藏鍵盤。這種方法,太山寨了。爲了相應一個事件增長一個button太不值得的。 ui

第二種方法:在背景圖片上添加Tap事件,相應單擊處理。這種方法,很好代替了button方式,可是若是UI上沒有背景圖片,這種方法又回到到第一種山寨的方法行列中。 spa

[plain] view plain copy
  1. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  2. - (void)viewDidLoad  
  3. {  
  4.     [super viewDidLoad];  
  5.       
  6.     // 添加帶有處理時間的背景圖片  
  7.     UIImageView *backView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];  
  8.     backView.image = [UIImage imageNamed:@"small3.png"];  
  9.       
  10.     backView.userInteractionEnabled = YES;  
  11.     UITapGestureRecognizer *singleTouch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];  
  12.     [backView addGestureRecognizer:singleTouch];  
  13.       
  14.     backView.tag = 110;  
  15.     [self.view addSubview:backView];  
  16.       
  17.     // 添加uitextfield  
  18.     text = [[UITextField alloc] initWithFrame:CGRectMake(30, 150, 250, 31)];  
  19.     //[text setBackgroundColor:[UIColor grayColor]];  
  20.     text.borderStyle = UITextBorderStyleRoundedRect;  
  21.     text.placeholder = @"";  
  22.     [self.view addSubview:text];  
  23.     // 添加返回按鈕  
  24.       
  25.     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  26.     button.frame = CGRectMake(125, 40, 75, 35);  
  27.     [button addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchUpInside];  
  28.     //[button setBackgroundColor:[UIColor grayColor]];  
  29.     [button setTitle:@"返回" forState:UIControlStateNormal];  
  30.       
  31.     [self.view addSubview:button];  
  32. }  
  33.   
  34. -(void)dismissKeyboard:(id)sender{  
  35.     [text resignFirstResponder];  
  36. }  

第三種方法:在xib文件中,修改xib文件的objects屬性,默認是view屬性,咱們能夠修改成UIControl屬性,從而是xib文件 相應touch down事件。這種方法,缺點就是沒有xib就悲劇了。不過按說也應該能夠動態設置,目前沒有找到方法,那位網友知道的話,不妨告訴我下。 .net

設置參考這裏: orm

把objects設置未control後,能夠直接相應touch down事件 blog


綜合以上三種方法,編寫了一個例子,你們能夠下載看看代碼 事件


代碼點擊這裏下載 下載代碼
相關文章
相關標籤/搜索