在iOS上出現軟鍵盤後,但願點擊非鍵盤部分,隱藏鍵盤,即便鍵盤消失的方法討論。 ide
第一種方法:增長一個button,相應touch down事件,隱藏鍵盤。這種方法,太山寨了。爲了相應一個事件增長一個button太不值得的。 ui
第二種方法:在背景圖片上添加Tap事件,相應單擊處理。這種方法,很好代替了button方式,可是若是UI上沒有背景圖片,這種方法又回到到第一種山寨的方法行列中。 spa
- // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
- // 添加帶有處理時間的背景圖片
- UIImageView *backView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
- backView.image = [UIImage imageNamed:@"small3.png"];
-
- backView.userInteractionEnabled = YES;
- UITapGestureRecognizer *singleTouch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
- [backView addGestureRecognizer:singleTouch];
-
- backView.tag = 110;
- [self.view addSubview:backView];
-
- // 添加uitextfield
- text = [[UITextField alloc] initWithFrame:CGRectMake(30, 150, 250, 31)];
- //[text setBackgroundColor:[UIColor grayColor]];
- text.borderStyle = UITextBorderStyleRoundedRect;
- text.placeholder = @"";
- [self.view addSubview:text];
- // 添加返回按鈕
-
- UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
- button.frame = CGRectMake(125, 40, 75, 35);
- [button addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchUpInside];
- //[button setBackgroundColor:[UIColor grayColor]];
- [button setTitle:@"返回" forState:UIControlStateNormal];
-
- [self.view addSubview:button];
- }
-
- -(void)dismissKeyboard:(id)sender{
- [text resignFirstResponder];
- }
第三種方法:在xib文件中,修改xib文件的objects屬性,默認是view屬性,咱們能夠修改成UIControl屬性,從而是xib文件 相應touch down事件。這種方法,缺點就是沒有xib就悲劇了。不過按說也應該能夠動態設置,目前沒有找到方法,那位網友知道的話,不妨告訴我下。 .net
設置參考這裏: orm
把objects設置未control後,能夠直接相應touch down事件 blog
綜合以上三種方法,編寫了一個例子,你們能夠下載看看代碼 事件
![](http://static.javashuo.com/static/loading.gif)
代碼點擊這裏下載
下載代碼