[英]how to detect event touch in subview or how to make parent view was touched when we touch subview?
我有2個UIView。
第一個是父視圖
第二個是子視圖,
我們如何檢測子視圖何時觸及?
或者我想讓用戶觸摸子視圖時觸摸父視圖,任何代碼都可以幫我做到嗎? 是否有可能做到這一點?
因為我有一個Something Function,當其中一個被觸摸時會調用。
這對我有用:
(在xib或storyboard中鏈接子視圖)
ViewController.h
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UIView *subview;
@property (nonatomic, strong) UITapGestureRecognizer *tapRecognizer;
@end
ViewController.m
@implementation ViewController
@synthesize subview;
@synthesize tapRecognizer;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTap:)];
[subview addGestureRecognizer:tapRecognizer];
}
- (IBAction)handleTap:(UITapGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateEnded){
//code here
NSLog(@"subview touched");
}
}
@end
問題已經解決了。 我覺得有人給了一個很好的答案,但我忘記了。
這就是我做的。 XIB中有一個選項。 有一個復選框(標題為“啟用了用戶交互”),指定子視圖是否處理用戶事件。
取消選中該復選框,並且所有觸摸子視圖都會轉到父視圖或其后的任何其他視圖。
要檢測觸摸事件,您需要在子視圖或超級視圖中添加UITapGestureRecognizer
(您需要在其中進行觸摸)。
- (void)viewDidLoad
{
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tap:)];
tap.numberOfTapsRequired = 1;
[self addGestureRecognizer:tap];
[super viewDidLoad];
}
然后你可以添加UITapGestureRecognizer
委托方法
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [touches anyObject];
// here you can get your touch
NSLog(@"Touched view %@",[touch.view class] );
}
希望它能給你一些想法......
這可能有所幫助:
UITouch *touch = [event.allTouches anyObject];
CGPoint touchPoint = [touch locationInView:YOUR VIEW NAME];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.