Iphone Textview不会调用TouchesBegan

时间:2010-11-16 20:50:04

标签: iphone uitextfield uitextview touchesbegan

当我触摸屏幕上的其他位置时,我有一个隐藏键盘的Textfield(通过我的TouchesBegan功能并且辞职......等等)。但是当我触摸Textview时,TouchesBegan不会被调用而键盘也不会隐藏!有没有办法调用TouchesBegan来隐藏键盘?

3 个答案:

答案 0 :(得分:2)

我见过的最好的方法是添加一个透明的子视图,它覆盖文本视图并首先处理TouchesBegan。然后,您可以检测文本字段外的触摸,并通过将文本字段作为第一响应者辞职来关闭键盘。

例如,无论哪种方式,都可以在IB中或以编程方式创建叠加子视图。放置并调整大小以使其覆盖文本视图,并为其提供清晰的颜色。如果您通过IB添加视图,请在主视图加载时将其隐藏,以便它不会吸收触摸,如下所示:

- (void)viewDidLoad
{
    [super viewDidLoad];
    overView.hidden = YES;
}

然后,当文本字段开始编辑时,取消隐藏视图:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    overView.hidden = NO;
}

当文本字段结束编辑时,请重新隐藏视图:

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    overView.hidden = YES;
}

添加touchesBegan以检测何时触摸未隐藏的overView:

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

    // Resign first responder if touch is outside text field
    if ([touch view] != myTextField)
        [myTextField resignFirstResponder];

    // Send touches up the responder chain (pass them through)
    [self.nextResponder touchesBegan:touches withEvent:event];
}

您也可以通过自定义手势执行此操作,但这仅适用于iOS 4.x,在我看来,更复杂。

答案 1 :(得分:2)

还有一种在touchesBegan上隐藏键盘的简单方法:当您使用UITextView输入数据时。

步骤1.确保在类声明时扩展了Textviewdelegate。

  

@interface YourClassName:UIViewController {     IBOutlet UITextView * txtMyView; }

步骤2.将委托设置为自己在视图中执行加载功能。

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

步骤3.使用textView名称在touchesbegan函数中编写similer代码。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
            [txtMyView resignFirstResponder];
        [super touchesBegan:touches withEvent:event];

}

谢谢和问候。

答案 2 :(得分:2)

我假设您的UITextView不可编辑,因为您不希望键盘在触摸时弹出,因此请确保在UITextView的View属性中未选中“User Interaction Enabled”。你也可以在ViewController中写这个:

textView.userInteractionEnabled = NO;

这将允许用户事件传递到superview,并且将调用touchesBegan和其他委托方法。