UIView 不响应触摸



我有一个简单的视图控制器,我使用以下代码为窗口添加了类似子视图的控制器:

UIWindow *window = [UIApplication sharedApplication].keyWindow;
if (!window)
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
self.view.alpha = 0.0;
self.view.userInteractionEnabled = YES;
[window addSubview:self.view];
[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc]    initWithTarget:self action:@selector(closeTriggered:)]];
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
  self.view.alpha = 1.0;
    }completion:nil];

但当我点击这个视图时,什么也没发生。即使是事件触摸Began:也不被调用。

UPD:上面的代码在-(void)show方法中。我想在所有控制器之上显示一个控制器。在FirstViewController中,我创建了CustonAlertViewController的实例,如下所示:

CustomAlertViewController *alertVC = [[CustomAlertViewController alloc]init];
[alertVC show];

在CustomAlertViewController中,我在顶部显示了show方法,viewDidLoad方法带有:

self.view.backgrondColor = [UIColor greenColor];

隐藏视图(相当于具有alpha == 0.0的视图)不会对触摸做出响应。如果需要完全透明的视图,请将alpha保留为>0.0,然后说。。。

self.view.backgroundColor = [UIColor clearColor];

或者,指定一个非零alpha。

EDIT是的,在调用show之后立即释放CustomAlertViewController实例。进行分配的视图控制器需要有一个强大的属性来保持警报,

@property(nonatomic,strong) CustomAlertViewController *alertVC;

并添加。。。

CustomAlertViewController *alertVC = [[CustomAlertViewController alloc]init];
self.alertVC = alertVC;
[alertVC show];

这并没有试图解决超出此问题范围的一些潜在问题(如旋转,或在警报完成后干净地恢复)。

//这样尝试,你需要给出的触摸次数

  UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]   initWithTarget:self action:@selector(closeTriggered:)];
 gesture.numberOfTapsRequired = 1;
        gesture.numberOfTouchesRequired = 1;
[self.view addGestureRecognizer:gesture];

在将addSubview设置到窗口后,您一直在设置UITapGestureRecognizer。类似:

您一直在这样做

//...
[window addSubview:self.view];
[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc]    initWithTarget:self action:@selector(closeTriggered:)]];
//...


试试这个

先设置UITapGestureRecognizer,然后再设置addSubview。记住将UIGestureRecognizerDelegate添加到您的ViewController

self.view.alpha = 0.2;
self.view.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeTriggered:)];
tapGesture.numberOfTapsRequired = 1;
[tapGesture setDelegate:self];
[self.view addGestureRecognizer:tapGesture];
// After you add your self.view to window
[window addSubview:self.view];

我希望这能帮助你。

最新更新