代码之家  ›  专栏  ›  技术社区  ›  Ankit Sachan

UIScrollView中UITextField的handle TouchesBegind方法

  •  2
  • Ankit Sachan  · 技术社区  · 16 年前

    touchesBegan 用于文本字段。此文本字段位于scrollview中。

    到目前为止,我试过:

    我创建了UIScrollView的一个子类

    @interface CustomScrollView : UIScrollView
    {
    }
    @end
    
    @implementation CustomScrollView
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        NSLog(@"good");
    }
    
    @end
    

    和我用textfields实现的一样。我创建了一个 UITextField :

    @interface CustomTextField : UITextField
    {
    }
    @end
    
    @implementation CustomTextField
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        NSLog(@"good");
    }
    
    @end
    

    如果文本字段位于普通视图内,则此操作正常,但如果文本字段位于常规scrollView或我的自定义scrollView内,则此操作失败。

    请告诉我这件事

    (我这样做的目的是当用户长按textfield时,textfield中的文本从textfield分配到标签,用户可以将此标签拖动到视图中的其他位置)

    2 回复  |  直到 16 年前
        1
  •  6
  •   please delete me please delete me    16 年前

    默认情况下,UIScrollView会延迟向其子视图发送触摸事件,直到它能够确定触摸是否会导致滚动。你可以通过点击并按住你的文本字段来证明这一点——触摸开始会在片刻后触发。

    _myCustomScrollView.delaysContentTouches = NO;
    

    如果您想在这两个方面都做到最好(用户可以从任何地方滚动,并且子视图可以响应触摸),您可以覆盖CustomScrollView中的hitTest方法,并向已触摸的子视图发送消息。以下是CustomScrollView中的实现:

    -(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent*)event {
        UIView *hitView = [super hitTest:point withEvent:event];
    
        if([hitView class] == [CustomTextField class]) {
            [(CustomTextField *) hitView handleTap:point]; 
        } 
    
        return hitView;
    }
    

    下面是CustomTextField的实现:

    @interface CustomTextField : UITextField {
    
    }
    
    -(void) handleTap:(CGPoint) point;
    
    @end
    
    @implementation CustomTextField
    
    -(void) handleTap:(CGPoint) point {
        // Implement your handling code here
    }
    
    @end
    

    这是一个黑客,因为它不是真正处理触摸(touchsbegind、touchsended等),但它可以工作。

        2
  •  3
  •   Arne    14 年前

    我还实现了一个CustomUIScrollView作为UIScrollView的子类,并重写了TouchesBegind方法:

    - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        if (!self.dragging)
        {
            [self.nextResponder touchesBegan:touches withEvent:event];
        }
        else
        {
            [super touchesBegan:touches withEvent:event];
        }
    }
    

    在interfacebuilder中,我将scrollview对象的自定义类设置为CustomUIScrollView,并在“触摸”第一部分中禁用可取消的内容触摸。现在,我可以使用UITextField的ViewController中的touchesbeent方法,在检测到键盘外的触摸时,让键盘消失。

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch *touch = [[event allTouches] anyObject];
        if ([myTextField isFirstResponder] && [touch view] != myTextField)
        {
            [myTextField resignFirstResponder];
        }
        [super touchesBegan:touches withEvent:event];
    }