2009-12-19 33 views
2

我在這裏有一種情況,我必須爲文本字段處理touchesBegan。此文本字段處於滾動視圖。在UIScrollView中爲UITextField處理touchesBegan方法

我想這個至今:

我做的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 

這工作正常,如果文本字段是一個普通視圖中,但是當文本字段是一個普通的滾動視圖或我的自定義滾動視圖中失敗。

請賜教這個

(我這樣做是爲了達到這樣的事情,當用戶長按在文本框的文本是從文本字段分配一個文本框的標籤,用戶可以在此標籤拖動到其他地方在視圖中)

回答

6

默認情況下,UIScrollView延遲向其子視圖發送觸摸事件,直到它可以確定觸摸是否應該導致滾動爲止。你可以通過點擊並按住你的文本字段來證明這一點 - touchBeBe會在一會兒之後觸發。

要解決,只需將自定義滾動視圖的delaysContentTouches屬性設置爲NO。這可以通過取消選中「延遲內容接觸」通過Interface Builder來完成。在代碼,只需做一些類似以下的東西:

_myCustomScrollView.delaysContentTouches = NO; 

您CustomTextField的方法的touchesBegan現在將立即觸發。但是,請注意,如果用戶的初始抽頭位於任何子視圖內,用戶將不再能夠在CustomScrollView內滾動。如果delayContentTouches設置爲no,請嘗試點擊文本字段(或任何子視圖)並輕掃 - 您將看到不會發生滾動。當delayContentTouches設置爲yes時,用戶可以在CustomScrollView邊界內的任意位置點按並滑動,並使其滾動。

如果您想要兩全其美(用戶可以從任何地方滾動,並且可以響應觸摸的子視圖),您可以覆蓋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 

這是一個黑客,因爲它不是真正的處理觸摸(的touchesBegan,touchesEnded等),但它作品。

+0

你救了我的一天;) – DeZigny 2012-07-18 21:43:48

3

我實現以及一個CustomUIScrollView作爲UIScrollView中的一個子類,並覆蓋了的touchesBegan方法:

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

InterfaceBuilder下我的自定義類滾動視圖對象設置爲CustomUIScrollView和在我去激活「觸摸」的一部分可取消的內容接觸。現在,我可以在我的UITextField的ViewController中使用touchesBegan方法,以便在檢測到鍵盤外部的觸摸時讓鍵盤消失。

- (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]; 
} 
相關問題