0

我想在 iPhone 上点击背景时做点什么。

如何启用后台点击?

我使用此代码在我的应用程序上放置了一个示例背景。

- void viewDidLoad{

     [super viewDidLoad];
     UIGraphicsBeginImageContext(self.view.frame.size);
     [[UIImage imageNamed:@"backgroundimage.jpeg"] drawInRect:self.view.bounds];
     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
}

如何进行后台窃听?

例如我想点击背景,会弹出一条消息“背景被点击了!” .

我需要IBAction吗?

需要帮忙。

4

2 回答 2

0

您可以做的是使用 IBAction,这将是更简单的代码。

在视图控制器的头文件中,执行以下操作:

- (IBAction)backgroundTap:(id)sender;

在视图控制器的实现文件中,执行以下操作:

- (IBAction)backgroundTap:(id)sender
{

}

在情节提要中,假设您已将视图控制器 GUI 与视图控制器类链接起来,单击视图控制器 GUI 的背景,然后在 Utilities 视图中显示 Identity Inspector,该视图应显示在右侧。然后,在当前应该为空白的自定义类下,输入 UIControl。现在转到连接检查器并在 Touch Down 链接到背景,选择 backgroundTap。现在,backgroundTap 方法中的任何内容都将在您选择背景时发生。

于 2013-08-05T14:12:21.370 回答
-1

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:
UIButtonUITapGestureRecognizer

于 2013-08-05T11:09:05.423 回答