按下视图时关闭键盘 - Obj C.

时间:2015-01-17 08:25:52

标签: ios objective-c

我有一个函数可以将一些字段填充到self.view.window视图中。现在,如果我跑:

/* HIDE KEYBOARD WHEN CLICKED AWAY */
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    gestureRecognizer.cancelsTouchesInView = NO; //so that action such as clear text field button can be pressed
    [self.view addGestureRecognizer:gestureRecognizer];

在我的viewDidLoad内,效果很好。但我们可以点击cell -> calls function -> displays using: [self.view.window addSubview:self.DatePicker];

我的gestureRecognizer将不再有效。我认为这是因为它发送到window。我的问题是,我怎样才能让它发挥作用?

更新:

我添加到window的原因是因为我需要给它一个fixed类似的属性,这对我有用。例如,在CSS中,您可以执行position:fixed;

2 个答案:

答案 0 :(得分:0)

在视图上添加TAP GESTURE

    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBehind:)];
    recognizer.delegate  = self; 
    [recognizer setNumberOfTapsRequired:1];
    recognizer.cancelsTouchesInView = NO; //So the user can still interact with controls in the modal view
    [self.view.window addGestureRecognizer:recognizer];

handleTapBehind方法:

- (void)handleTapBehind:(UITapGestureRecognizer *)sender
{
          [self.view.window removeGestureRecognizer:sender];
          // Dismiss Your Keyboard HERE    
}

答案 1 :(得分:0)

我想出了一个廉价的解决方法,但如果你有更好的主意,请告诉我。

因为我有一个填充在uitableview中的单元格,我正在侦听单击的特定单元格。所以我所做的只是创建一个gesture容器,然后将其添加到我收听的那个特定单元格的view.window上,并确实具有魅力。

[self.view.window addGestureRecognizer:self.gestureRecognizer];