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

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

最佳答案

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

- (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”协议(protocol)并设置委托(delegate)(使用您的变量):
self.tapOutside.delegate = self;

干杯

关于ios - UITextfield的清除按钮在UIScrollView内部时会隐藏键盘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10126324/

10-14 21:30