UITextfield的清除按钮在UIScrollView内部隐藏键盘

时间:2012-04-12 15:04:32

标签: ios xcode uiscrollview uitextfield

我在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;
    }

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

2 个答案:

答案 0 :(得分:13)

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

- (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"协议并设置委托(使用你的vars):

self.tapOutside.delegate = self;

干杯

答案 1 :(得分:2)

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

-(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,就像使用clear按钮的情况一样,但如果他们触摸通常会执行您的手势代码的普通按钮,仍会隐藏键盘