UIWindow addSubview 处理事件

UIWindow addSubview handle events

我想通过 UIViewController 构建一个 自定义警报 ,并将其视图作为子视图添加到当前 window。视图显示很好,但我无法处理任何触摸事件。

我试过很多次给这个viewcontroller加一个按钮,加一个目标。我也尝试添加一个 UITapGestureRecognizer 并将视图的 userInteractionEnabled 设置为 true,但是即使我清除了所有子视图,这也失败了。

我是不是漏掉了什么?

代码如下:

CustomAlert Viewcontroller:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor clearColor];

    backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    backgroundView.backgroundColor = [UIColor blackColor];
    backgroundView.alpha = 0.5;
    [self.view addSubview:backgroundView];


    backImage = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 300) / 2, (self.view.frame.size.height - 250) / 2, 300, 250)];

    backImage.image = [UIImage imageNamed:@"AlertBackground"];
    [self.view addSubview:backImage];

    confirmButton = [[UIButton alloc]initWithFrame:CGRectMake( backImage.frame.origin.x + 100 , backImage.frame.origin.y + 250 - 40, 100, 26)];
    [self.view addSubview:confirmButton];
    [confirmButton addTarget:self action:@selector(confirmButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    confirmButton.backgroundColor = [UIColor redColor];
    [confirmButton setTitle:@"click me" forState:UIControlStateNormal];
}

-(void)confirmButtonClick:(UIButton*)sender{

    [self.view removeFromSuperview];
}

-(void)show{
    UIWindow * window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
    [window addSubview:self.view];
}

方法调用自定义警报:

CustomAlert * alert = [[CustomAlert alloc]init];
[alert show];

尝试用这些重写你的 -show{} 方法

UIWindow * window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
[window.rootViewController.view addSubview:self.view];

更新: 如果之前没有帮助,请尝试覆盖

-(void)show{
    UIWindow * window = (UIWindow*)[UIApplication sharedApplication].keyWindow;

    [window.rootViewController addChildViewController:self];
    [window.rootViewController.view addSubview:self.view];
    [self didMoveToParentViewController:window.rootViewController];
}

这三种方式建立亲子关系