2009-10-22 29 views
2

我已經做了以下的viewcontroller.m的viewDidLoad中觸摸事件不起作用?在UImageview中?

img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; 
img.multipleTouchEnabled = YES; 
[self.view addSubview:img]; 
[img release]; 

但Touchbegan,碰動了,一切都沒有工作,當我通過斷點檢查? 而不是這個,當我使用XIB文件,我設置了multipleTouchEnabled,但在 觸摸事件不工作... anyHelp?請?

回答

3

你應該嘗試設置該屬性:

img.userInteractionEnabled = YES; 

但這是不夠的, ,因爲這些方法:

– touchesBegan:withEvent: 
– touchesMoved:withEvent: 
– touchesEnded:withEvent: 

是從UIResponder類(基類的UIView),而不是UIViewController。

所以,如果你想讓它們被調用,你必須定義一個UIView的子類(或者在你的情況下是UIImageView),以覆蓋基本方法。

實施例:

MyImageView.h

@interface MyImageView : UIImageView { 
} 

@end 

MyImageView.m

@implementation MyImageView 

- (id)initWithFrame:(CGRect)aRect { 
    if (self = [super initWithFrame:rect]) { 
     // We set it here directly for convenience 
     // As by default for a UIImageView it is set to NO 
     self.userInteractionEnabled = YES; 
    } 
    return self; 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    // Do what you want here 
    NSLog(@"touchesBegan!"); 
} 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    // Do what you want here 
    NSLog(@"touchesEnded!"); 
} 

@end 

然後,可以與視圖控制器您的示例實例化一個MyImageView:

img = [[MyImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; 
[self.view addSubview:img]; 
[img release]; 

你應該看到觸摸事件(假設self.view將userInteractionEnabled設置爲YES)。

+0

謝謝,我已經完成.... – 2009-10-22 11:44:27

+0

一個更正,UIViewCOntroller也繼承自UIResponder。如果您翻轉UIImageView的userInteractionEnabled標誌,則它將成爲響應者鏈的一部分。而且,如果您不處理UIImageView子類中的觸摸事件(您不需要),則會將該WILL傳遞到鏈中並最終到達管理視圖層次結構的UIViewController子類。 – 2009-12-01 17:31:59