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];
}
BTW,沒有必要繪製背景圖片,因爲[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
還不算晚。
您之前是否曾使用過Tap Gesture Recognisers?如果沒有,那麼我建議你按照這個教程開始: http://www.raywenderlich.com/6567/uigesturerecognizer-tutorial-in-ios-5-pinches-pans-and-more –
嘗試UIButton或,作爲Puneet建議,UIGestureRecognizer。 – johnyu