UitextField resignFirstResponder does not work in scroll view

旧巷老猫 提交于 2019-12-19 11:35:26

问题


I have 2 functions to resignFirstResponder but neither of them works when the textfields are in scrollview

my functions:

-(BOOL)textFieldShouldReturn:(UITextField *)theTextField {

        if (theTextField == textField1) {
        [textField1 resignFirstResponder];
    }
    if (theTextField == textField2) {
        [textField2 resignFirstResponder];
    }
    if (theTextField == textField3) {
        [textField3 resignFirstResponder];
    }


    return YES;

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    [textField1 resignFirstResponder];
    [textField2 resignFirstResponder];
    [textField3 resignFirstResponder];

}

I have linked the scroll view in IB, I can not find out why it does not works there only when I click outside of scrollview.so it only responds to view, but why?I thougth that [[event allTouches] anyObject] respond to ALLtouches at ANYObjects

Thanks for help


回答1:


Wouldn't it be a bit more elegant to add a transparent view that inherits UIControl with the size that equal to your scroll view to the very back of it and then just create IBAction for this new view?




回答2:


You can also use a gesture recognizer to get the background tap. Use cancelsTouchesInView = NO to forward all other touches to the right receivers.

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTappedBackground:)];
tapGesture.cancelsTouchesInView = NO;
[self.scrollView addGestureRecognizer:tapGesture];



回答3:


@interface ScrollView <UIScrollViewDelegate,UITextFieldDelegate> {
    UITextField *_currentTF;
}

@implementation

- (void)viewDidLoad {
    yourScrollView.delegate = self;
    yourTextField.delegate = self;
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_currentTF resignFirstResponder];
}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    _currentTF = textField;
    return YES;
}


来源:https://stackoverflow.com/questions/5089845/uitextfield-resignfirstresponder-does-not-work-in-scroll-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!