UIButton
是最简单的方法。
- (void)backgroundButtonClicked:(id)sender
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"Background was tapped!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
- (void)viewDidLoad
{
[super viewDidLoad];
/*
* Your other code here
*/
UIButton *backgroundButton = [UIButton buttonWithType:UIButtonTypeCustom];
backgroundButton.backgroundColor = [UIColor clearColor];
backgroundButton.frame = self.view.bounds;
[backgroundButton addTarget:self action:@selector(backgroundButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:backgroundButton];
[self.view sendSubviewToBack:backgroundButton];
}
[UIImage imageNamed:@"imagename"]
顺便说一句,由于返回图像,因此无需绘制背景图像。如果您想展示它,请尝试将代码放入您的-viewDidLoad
:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"backgroundimage.jpeg"]];
imageView.frame = self.view.bounds;
[self.view insertSubview:imageView belowSubview:backgroundButton];
[imageView release];
编辑:
感谢@AlexMDC 提醒我UITapGestureRecognizer
. 这是UITapGestureRecognizer
版本:
- (void)tapped:(UITapGestureRecognizer *)g
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"Background was tapped!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
- (void)viewDidLoad
{
[super viewDidLoad];
/*
* Your other code here
*/
UITapGestureRecognizer*tap = [[UITapGestureRecognizer alloc] init];
[tap addTarget:self action:@selector(tapped:)];
[self.view addGestureRecognizer:tap];
[tap release];
}
两个版本都满足要求。不可否认,UITapGestureRecognizer
它更强大,更灵活。但是,这次我更愿意UIButton
做这个把戏。它比手势识别器更轻量级。我不需要关心手势识别器的状态,触摸事件是否被它阻止或如何实现UIGestureRecognizerDelegate
.
更有可能我们想在控制器的视图上添加一些其他UIView
的或子类。UIView
此时,版本需要排除委托方法UITapGestureRecognizer
中的所有非背景区域。
如果检测双击是新的需求,现在重构.– gestureRecognizerShouldBegin:
UIButton
UITapGestureRecognizer