Castiel
Castiel

Reputation: 35

UIWindow addSubview handle events

I want to build a custom alert by UIViewController and add its view as a subview to the current window. The view displays very well, but I can't handle any touch events.

I have tried many times to add a button to this viewcontroller and add a target. I have also tried adding a UITapGestureRecognizer and set view's userInteractionEnabled to true, but this also failed even when I cleared all subviews just left the button.

Have I missed something?

Here is the code:

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];
}

Method call custom alert:

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

Upvotes: 0

Views: 1767

Answers (1)

Mr.Fingers
Mr.Fingers

Reputation: 1144

Try to rewrite your -show{} method with these

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

UPDATE: And if previous don't help, try to overwrite

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

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

Those three methods establish parent-child relations.

Upvotes: 0

Related Questions