[英]Tapping the Background image on iPhone
在iPhone上點擊背景時,我想做些事情。
如何啟用后台點擊?
我使用此代碼在我的應用程序上放置了示例背景。
- void viewDidLoad{
[super viewDidLoad];
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"backgroundimage.jpeg"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
如何進行背景攻牙?
例如,我想單擊背景,然后會彈出一條消息“ 背景被輕按!”。 。
我需要IBAction嗎?
需要幫忙。
您可以做的是使用IBAction,這將是簡單得多的代碼。
在視圖控制器的頭文件中,執行以下操作:
- (IBAction)backgroundTap:(id)sender;
在視圖控制器的實現文件中,執行以下操作:
- (IBAction)backgroundTap:(id)sender
{
}
在情節提要中,假設您已將視圖控制器GUI與視圖控制器類鏈接起來,請單擊視圖控制器GUI的背景,然后在“實用程序”視圖中顯示Identity Inspector,該視圖應顯示在右側。 然后,在當前應為空的自定義類下,鍵入UIControl。 現在轉到連接檢查器,並在Touch Down處鏈接到背景,選擇backgroundTap。 現在,backgroundTap方法中的所有內容都將是您選擇背景時發生的情況。
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
仍為時不晚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.