[英]Touch Event on UIView
有沒有人有任何示例代碼來檢測動態創建的 UIView 上的觸摸? 我發現了一些對 touchesBegan 的引用,但無法弄清楚如何實現它......
一個非常通用的方法是在自定義 UIView 子類中覆蓋這些方法:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
這些方法的官方文檔位於UIResponder 類文檔中的“響應觸摸事件”下(UIView 繼承了這些方法,因為它是 UIResponder 的子類)。 更長和更多的介紹性文檔可以在iOS的事件處理指南中找到。
如果您只想檢測點擊(在您的視圖中觸摸,然后觸摸),最簡單的方法是添加一個UIButton
作為您視圖的子視圖,然后添加您自己的自定義方法作為該按鈕的目標/操作對. 默認情況下,自定義按鈕是不可見的,因此它不會影響視圖的外觀。
如果您正在尋找更高級的交互,那么了解UIGestureRecognizer
類也很好。
在 UIView 上使用 UIAnimation 創建觸摸事件,您可以在任何地方管理 UIView 上的觸摸。
以下代碼:這里 self.finalScore 是一個 UIView ,cup 是一個 UIImageView 。 我處理
UIImageView 上的觸摸事件,它出現在 UIView 中。
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch1 = [touches anyObject];
CGPoint touchLocation = [touch1 locationInView:self.finalScore];
CGRect startRect = [[[cup layer] presentationLayer] frame];
CGRectContainsPoint(startRect, touchLocation);
[UIView animateWithDuration:0.7
delay:0.0
options:UIViewAnimationCurveEaseOut
animations:^{cup.transform = CGAffineTransformMakeScale(1.25, 0.75);}
completion:^(BOOL finished) {
[UIView animateWithDuration:2.0
delay:2.0
options:0
animations:^{cup.alpha = 0.0;}
completion:^(BOOL finished) {
[cup removeFromSuperview];
cup = nil;}];
}];
}
像 UITapGestureRecognizer 是處理 UIView 上觸摸事件的另一種方式......
UITapGestureRecognizer *touchOnView = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(releaseButAction)] autorelease];
// Set required taps and number of touches
[touchOnView setNumberOfTapsRequired:1];
[touchOnView setNumberOfTouchesRequired:1];
// Add the gesture to the view
[[self view] addGestureRecognizer:touchOnView];
從您通過繼承UIView
創建的子類創建您自己的自定義UIView
並覆蓋子類中的以下方法,
(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
}
我建議將 UIView 父類更改為 UIControl,而不是使用手勢捕獲觸摸,以便它可以處理 touchUpInside 事件
從:
@interface MyView : UIView
到:
@interface MyView : UIControl
然后添加此行以供查看-
[self addTarget:self action:@selector(viewTapped:) forControlEvents:UIControlEventTouchUpInside];
因為手勢可能會在滾動時產生問題。
我的方法是簡單地將UIView
更改為 InterfaceBuilder IdentityInspector 中的UIControl
類,然后 ConnectionsInspector 將立即為掛鈎准備好觸摸事件。
零代碼更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.