2012-03-12 60 views
3

裏面我想檢測觸摸子視圖內touchesMoved檢測子視圖

在我的主視圖控制器我加入了一個名爲子視圖:SideBarForCategory,它從屏幕左邊的30% - 作爲一個側邊欄。

SideBarForCategory *sideBarForCategory = [[SideBarForCategory alloc] initWithNibName:@"SideBarForCategory" bundle:nil]; 
[sideBarData addSubview:sideBarForCategory.view]; 

內SideBarForCategory,我想測試觸摸

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [[event touchesForView:self.view] anyObject]; 

    CGPoint location = [touch locationInView:touch.view]; 
    NSLog(@"Map Touch %f",location.x); 

} 

上面的代碼(touchesMoved)完美地工作在主視圖(視圖 - 控制),但我的子視圖(SideBarForCategory)內不工作 - 爲什麼以及如何修復它

+1

是你的側欄視圖'userInteractionEnabled'? – lukya 2012-03-12 13:14:14

+0

是的,所有視圖都是 – chewy 2012-03-12 13:20:33

回答

1

兩個可能的解決方案,我能想到的:

  1. 要麼使用GestureRecognizers(如UITapGestureRecognizer,UISwipeGestureRecognizer)和那些識別器添加到您的SideBarForCategory視圖。

  2. 通用手勢處理:創建您自己的UIView的自定義子類,例如MyView,並在其中添加這些觸摸方法。然後創建SideBarForCategory視圖作爲MyView的一個實例。

希望工程:)

更新時間: 對於第二個選項:

#import <UIKit/UIKit.h> 

@interface MyView : UIView 
@end 





@implementation MyView 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
    } 
    return self; 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    // No need to invoke |touchesBegan| on super 
    NSLog(@"touchesBegan"); 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    // invoke |touchesMoved| on super so that scrolling can be handled 
    [super touchesMoved:touches withEvent:event]; 
    NSLog(@"touchesMoved"); 
} 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    [super touchesEnded:touches withEvent:event]; 
    NSLog(@"touchesEnded"); 
} 

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { 
    /* no state to clean up, so null implementation */ 
    NSLog(@"touchesCancelled"); 
} 

/* 
// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect 
{ 
    // Drawing code 
} 
*/ 

@end 

更新: ,然後在SideBarCategoryView類的實現,裏面的loadView()

self.view = [[MyView alloc] init]; 
+0

你好亞丁,我的目標是ios 4或更好,所以我不知道手勢識別器是好的,你可以詳細說明選項2 – chewy 2012-03-12 13:29:51

+0

我認爲手勢識別器在ios 4或更高版本中工作良好。我自己多次使用它。無論如何,它總是取決於項目的需要。 – 2012-03-12 13:38:11

+0

@ShiShi:我希望這對你有用 – 2012-03-12 14:10:32

0

檢查Apple轉換點的參考。您可能會忘記轉換與您的子視圖相關的點。因此它試圖檢查觸點的絕對座標。

也許你需要的是:

- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view 
+0

謝謝,但即使點不正確,函數根本沒有被調用,我通過將NSlog更改爲NSLog(@「Map Touch」)來檢查它。 – chewy 2012-03-12 13:21:34

+0

通常情況下,接收觸摸的第一個應該是視圖層級中最低的一個,因此您不需要傳遞事件。手勢識別器解決方案可能是您的最佳選擇。 – 2012-03-12 13:31:14