ios - 向 UIImageView 添加点击手势以更改 UILabel?

标签 ios objective-c uiimageview uilabel uitapgesturerecognizer

几天来,我一直在 Xcode 6 中开发 iOS 单 View 应用程序,但在尝试添加触摸事件时遇到了障碍。这是我正在尝试做的事情:

在 Storyboard中,我创建了一个 UILabel 和一个 UIImageView,我想向 UIImageView 添加一个点击手势,这样当我点击图像时,标签会发生变化。虽然我不太习惯用 Objective-C 编程,但我明白我必须首先将手势附加到 UIImageView,然后我的事件处理程序方法可以处理它。这是我尝试过的:

在 ViewController.h 文件中:

   #import <UIKit/UIKit.h>

@interface ViewController : UIViewController {

    IBOutlet UIImageView *imageView;
    IBOutlet UILabel *myLabel;

}

-(void)handleTap:(id)sender;

@end

在 ViewController.m 文件中:

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {

imageView.userInteractionEnabled = YES;

UITapGestureRecognizer *pgr = [[UITapGestureRecognizer alloc]
                                 initWithTarget:self
                                         action:@selector(handleTap)];

[imageView addGestureRecognizer:pgr];

    [super viewDidLoad];
}

- (void)handleTap:(UITapGestureRecognizer *)tapGestureRecognizer
{
    myLabel.text = [NSString stringWithFormat:@"It Worked"];
}

我期望发生的是当点击 imageView 时 myLabel 会发生变化,myLabel 和 imageView 分别链接到 UILabel 和 UIImageView。我确实意识到,只需向 imageView 添加一个按钮,我就可以省去很多麻烦,但我真的想让它与触摸事件一起工作。

我是这门语言的新手,这是我第一次尝试构建一些东西。发布此内容时我已尝试尽可能详细,但如果您需要更多详细信息,我很乐意提供。非常感谢详细信息、代码示例和各部分如何组合在一起的解释。谢谢。

最佳答案

#import "ViewController.m"

@interface ViewController ()
{
    IBOutlet UILabel *myLabel;
    IBOutlet UIImageView *myImage;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Tapped:)];
    tap.numberOfTapsRequired = 1; //You can change this is double tap ect..
    Red.cancelsTouchesInView = YES;
    myImage.userInteractionEnabled = YES; //if you want touch on your image you'll need this
    [myImage addGestureRecognizer:tap];
}

-(void)Tapped:(UITapGestureRecognizer *)sender
{
    myLabel.text = [NSString stringWithFormat:@"It Worked"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

如果您的游戏仍然无法运行,则说明您还没有将标签和图像连接到界面生成器。要将它们连接到界面构建器,您需要将 do 变暗并将其连接到 View 中所需的对象,就像这张图片中那样,我单击该点并将其拖到标签上。 image for connecting

关于ios - 向 UIImageView 添加点击手势以更改 UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27712499/

相关文章:

ios - 如何创建 2 步可扩展的 tableview Swift

iphone - MapKit折线自定义缩放?

iphone - 将 NSMutableArray 转换为 C 结构体数组 - iPhone - OpenGL ES

iphone - 我可以使用 Objective-C block 并仍然在 iOS 4 之前的设备上运行吗?

ios - 在 uiimageview 中具有边框的着色区域

ios - 使 UIImageView 使用解析的照片来制作动画

ios - 如何在 CollectionView iOS 中停止自动重新加载和刷新图像

iphone - 使用标签栏和导航 Controller , View 被解除到错误的 View

ios - Google Places 添加的地方未显示

ios - 将小数点后 2 位的 float 舍入到 0.05 或 0.1