我有一个简单的 iPad 应用程序,其中包含以下 View 层:
BaseView
(覆盖整个可用区域)。SquareView
(覆盖 100x100px 区域)。
SquareView
作为 subview 添加到 BaseView
。
我还有一个 BaseViewController.m
文件。在这个文件中,我添加了 touchesBegan
和 touchesEnded
函数来处理触摸事件。问题是,当我点击 SquareView
时,touches 函数被调用,但是当我点击其他任何地方时,它们不会被调用。
我为 SquareView
设置了 userInteractionEnabled = YES
。我需要设置此变量才能接收触摸。
点击 SquareView
之外的区域不会触发触摸功能。我不明白为什么。在 BaseView
中设置 userInteractionEnabled
变量没有任何影响。这里会发生什么?我缺少一些规则吗?我很确定我曾经让它工作过。
当用户单击 subview (SquareView
) 时,我需要启动一个菜单(比如 MenuView
类)。这个想法是,当用户点击菜单(或 SquareView
)之外的区域时,我需要通过调用 [menuView removeFromSuperview ]
。有更好的方法来处理这个问题吗?
最佳答案
您可以尝试在 Controller 中使用此代码。它应该适合您。
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
subview.backgroundColor = [UIColor lightGrayColor];
[subview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(subviewTouched)]];
[self.view addSubview:subview];
[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(viewTouched)]];
}
- (void)viewTouched
{
NSLog(@"viewTouched");
}
- (void)subviewTouched
{
NSLog(@"subviewTouched");
}
关于ios - Superview 没有收到触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23199384/