6

我开发了我的应用程序,之后,我发现我需要添加一个滚动视图并将所有元素嵌入其中。这样做之后,我注意到键盘在键盘外触摸时不会消失。我知道是因为 IBAction 绑定到 ViewController 而不是滚动条。滚动条虽然不能有任何 IBAction。有什么办法可以帮助您解决这个问题吗?在添加滚动视图后,我搜索了很多并且有点迷失在隐藏键盘上。这个应该没那么复杂。

谢谢!

4

5 回答 5

19

iOS 7 中最干净的方式:

scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

斯威夫特版本:

scrollView.keyboardDismissMode = .interactive
于 2013-11-18T03:14:39.757 回答
6

请试试这个:

UITapGestureRecognizer *yourTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollTap:)];
    [scrollView addGestureRecognizer:yourTap];
    [self.view addSubview:scrollView];

然后在

- (void)scrollTap:(UIGestureRecognizer*)gestureRecognizer {

    //make keyboard disappear , you can use resignFirstResponder too, it depends.
    [self.view endEditing:YES];
}

***了不起,你说你必须将所有元素嵌入到滚动视图中吗?这意味着你已经添加了类似UIButton子视图的东西到滚动视图,然后当你初始化时你UIButton也应该添加动作,所以在 scrollTap 中只是 [self.view endEditting :YES] 就足够了,因为如果你在某个点按下UIScrollView并且如果那个点是UIButton,它将激活因为它会UIButton在你将它添加为子视图时停留在最上层,如果该点不是按钮,那么 scrollTap 将被激活。对不起,我没有仔细看,但应该像我说的那样。

于 2013-02-07T02:05:51.387 回答
2

根据@piam 的回答,这里是那些想要快速复制粘贴的人的快速版本:

//put this where you initialize your scroll view
var theTap = UITapGestureRecognizer(target: self, action: "scrollViewTapped:")
scrollView.addGestureRecognizer(theTap)

.

//This can go anywhere in your class
func scrollViewTapped(recognizer: UIGestureRecognizer) {
    scrollView.endEditing(true)
}

边注:

确保您的文本字段设置如下:

exampleTextField.delegate = self

并在您班级的顶部添加UITextFieldDelegate

class ViewController: UIViewController, UITextFieldDelegate {
于 2015-03-30T13:46:13.057 回答
0

我认为您可以UITapGestureRecognizer为 baseViewControlls 视图注册一个然后处理手势

- (void)handleTap:(UITapGestureRecognizer *)recognizer
{
    if(yourScrollView.yourTextField.isFirstResponder)
    {
        [yourScrollView.yourTextField resignFirstResponder];
    }
}

或者,当您的键盘显示时,您可以在 baseView 上添加一个透明蒙版按钮,该按钮位于键盘和 yourView 之间,并且按钮同时接收发送者,如下所示:

- (void)maskButton:(id)sender
{
    [_maskButton removeFromSuperView];
    if(yourScrollView.yourTextField.isFirstResponder)
    {
        [yourScrollView.yourTextField resignFirstResponder];
    }
}
于 2013-02-07T02:00:31.887 回答
0

要在触摸时立即关闭,而不是在点击时关闭:

添加一个 PanGestureRecognizer:

UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:nil action:nil];
panGR.cancelsTouchesInView = NO;
panGR.delegate = self;
[scrollView addGestureRecognizer:panGR];

实现手势委托:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    if (touch.phase == UITouchPhaseBegan) [self.view endEditing:YES];
    
    return NO;
}
于 2020-07-15T07:10:22.893 回答