当我们触摸子视图时,如何检测子视图中的事件触摸或如何触摸父视图?

时间:2011-08-02 05:32:47

标签: iphone xcode uiview subview

我有2个UIView。

第一个是父视图

第二个是子视图,

我们如何检测子视图何时被触及?

或者我想让用户触摸子视图时触摸父视图,任何代码都可以帮我做到吗?可以这样做吗?

因为我有一个Something Function,当其中一个被触摸时会调用。

4 个答案:

答案 0 :(得分:6)

这对我有用:

(在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

答案 1 :(得分:5)

问题已经解决了。我觉得有人给出了一个很好的答案,但我忘记了。

这就是我所做的。 XIB中有一个选项。有一个复选框(标题为“启用了用户交互”),指定子视图是否处理用户事件。

取消选中该复选框,并且所有触摸子视图都会转到父视图或其背后的任何其他视图。

答案 2 :(得分:3)

检测触摸事件,您需要在子视图或超级视图中添加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] );
}

希望它能给你一些想法......

答案 3 :(得分:0)

这可能会有所帮助:

UITouch *touch = [event.allTouches anyObject];
CGPoint touchPoint = [touch locationInView:YOUR VIEW NAME];