5

我在 UIScrollView 中有一个文本字段,我想在用户开始编辑时显示一个清除按钮。当用户点击 UIScrollview 的背景(但不是文本字段)时,我还需要隐藏键盘。显示那个清除按钮不是问题,问题是当点击清除按钮时键盘被隐藏并且文本字段没有被清除。显然,问题出在手势识别器上,因为处理此问题的方法会在单击清除按钮时触发(但在点击文本字段时不会触发)。这是我的代码:

    //adding gesture recognizer so i can hide keyboard when user taps scrollview
    - (void) textFieldDidBeginEditing:(UITextField *)textField
    {
        if (self.tapOutside == nil) self.tapOutside = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textFieldTouchOutSide:)];

        [self.scrollView addGestureRecognizer:self.tapOutside];
    }

    //This hides keyboard BUT IS ALSO CALLED WHEN CLEAR BUTTON IS TAPPED
    - (void)textFieldTouchOutSide:(id)sender
    {
        [self.textfield resignFirstResponder];
    }

    //NEVER GETS CALLED
    - (BOOL) textFieldShouldClear:(UITextField *)textField {
        return YES;
    }

任何想法如何解决这个问题?也许添加手势识别器的更好方法?我想不出没有优雅的解决方案......提前非常感谢......

4

2 回答 2

14

我遇到了同样的问题并通过以下方法解决了它:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    // Disallow recognition of gestures in unwanted elements
    if ([touch.view isMemberOfClass:[UIButton class]]) { // The "clear text" icon is a UIButton
        return NO;
    }
    return YES;
}

不要忘记遵守“UIGestureRecognizerDelegate”协议并设置委托(使用您的变量):

self.tapOutside.delegate = self;

干杯

于 2012-05-02T15:12:29.853 回答
3

我只是遇到了这个问题并且这个解决方案有效,但是如果您在视图上确实有其他按钮允许用户在填写表单时点击,您可以执行以下操作:

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
// Disallow recognition of gestures in unwanted elements
if ([touch.view isMemberOfClass:[UIButton class]] && [touch.view.superview isMemberOfClass:[UITextField class]]) { 

    // The "clear text" icon is a UIButton
    return NO;
}
return YES;
}

如果按钮是 UITextField 的子视图,这将缩小案例仅返回 No,就像清除按钮的情况一样,但如果他们触摸通常会执行您的手势代码的普通按钮,仍然隐藏键盘。

于 2012-05-18T15:29:06.340 回答