【问题标题】:UitextField resignFirstResponder does not work in scroll viewUitextField resignFirstResponder 在滚动视图中不起作用
【发布时间】:2011-07-02 16:03:37
【问题描述】:

我有 2 个函数可以 resignFirstResponder,但是当文本字段在滚动视图中时它们都不起作用

我的功能:

-(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];

}

我已经在 IB 中链接了滚动视图,我不知道为什么只有当我在滚动视图之外单击时它才在那里不起作用。所以它只响应视图,但是为什么?我认为 [[event allTouches] anyObject] 响应 ALLtouches在任何对象

感谢您的帮助

【问题讨论】:

    标签: objective-c cocoa-touch uiscrollview uitouch


    【解决方案1】:
    @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;
    }
    

    【讨论】:

    • 最好给你的答案一些解释
    【解决方案2】:

    您还可以使用手势识别器来获取背景点击。使用 cancelsTouchesInView = NO 将所有其他触摸转发给正确的接收者。

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

    【讨论】:

    • 你能给我等效的 swift 代码吗?谢谢
    【解决方案3】:

    在它的最后添加一个继承UIControl的透明视图,其大小等于你的滚动视图,然后为这个新视图创建IBAction,这不是更优雅吗?

    【讨论】:

    • 你的意思是我的视图有滚动视图并且它有一个透明的新视图?
    • 假设你有你的滚动视图。您应该通过 Interface Builder 在其上添加另一个 UIView。这个视图应该完全类似于您的滚动视图框架,并且应该低于您的所有文本字段。然后将它的类设置为 UIControl 并将您的 touchesBegan 方法更改为一些 IBAction 方法和使用此新方法的新视图的简单绑定 touchUpInside - 请参阅 iphonedevbook.com 上的源代码,第 4 章。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2014-02-06
    • 2015-07-22
    相关资源
    最近更新 更多