0

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

我已经尝试过很多次向这个视图控制器添加一个按钮并添加一个目标。我也尝试添加一个UITapGestureRecognizer并将视图设置userInteractionEnabledtrue,但即使我清除了所有子视图,这也失败了,只是离开了按钮。

我错过了什么吗?

这是代码:

CustomAlert 视图控制器:

- (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];
4

1 回答 1

0

尝试用这些重写您的 -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];
}

这三种方法建立了父子关系。

于 2016-08-30T09:15:25.443 回答