gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:34:44 27 4
gpt4 key购买 nike

几天来,我一直在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com