我想构建一个自定义警报UIViewController
并将其视图作为子视图添加到当前窗口。视图显示得很好,但我无法处理任何触摸事件。
我已经尝试过很多次向这个视图控制器添加一个按钮并添加一个目标。我也尝试添加一个UITapGestureRecognizer
并将视图设置userInteractionEnabled
为true
,但即使我清除了所有子视图,这也失败了,只是离开了按钮。
我错过了什么吗?
这是代码:
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];