我正在尝试从子类化的UIImageView添加点击手势,然后从视图控制器控制点击。我没有收到任何编译错误,但"addSubview"没有显示任何图像。如何使UIImageView显示?
如果我尝试从子类化的 UIImageVIew 控制点击和平移手势,我没有问题,但我想从视图控制器控制这些功能
相关代码如下所示。
UIImageView 子类
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
//self.userInteractionEnabled = YES;
previewController = [[PreviewController alloc]init];
[previewController self];
[self addSubview:character];
// Tap Initialization code
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:(PreviewController *)self.previewController action:@selector(addCharacter:)];
[self addGestureRecognizer:tap];
self.userInteractionEnabled = YES;
}
return self;
}
视图控制器
- (void)addCharacter:(UITapGestureRecognizer *)t
{
NSLog(@"add character");
imageNSArray = [NSMutableArray array];
uiImg = [UIImage imageNamed:@"homer.png"];
CGPoint loc = [t locationInView:self.view];
character = [[UIImageView alloc] initWithImage:uiImg];
character.center = loc;
[imageNSArray addObject:character];
//Locate the imageNSArray on frameImageView area only.
[self.view addSubview:character];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panCharacter:)];
[self.character addGestureRecognizer:pan];
character.userInteractionEnabled = YES;
}
视图放在子类化图像视图后面。将手势识别应用于新视图。您可以从新视图中控制点击手势。如果我不清楚,或者是否需要更多信息,请告诉我。
我认为你想要的是..你想在用户点击屏幕时显示图像。执行以下步骤:1. 将点击手势识别器拖放到视图控制器的默认视图上。2. 连接 (ctrl +) 手势识别器与视图控制器.m
看看这段代码。(刚刚修改了您的代码)
- (IBAction)onTap:(UITapGestureRecognizer *)sender {
NSLog(@"add character");
UIImage * uiImg = [UIImage imageNamed:@"sel.png"];
CGPoint loc = [sender locationInView:self.view];
UIImageView * character = [[UIImageView alloc] initWithImage:uiImg];
character.center = loc;
[self.view addSubview:character];
}
让我知道这是否不是你想要的...
编辑最好去这个代码...无需执行上述步骤。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];
[self.view addGestureRecognizer:tap];
self.view.userInteractionEnabled = YES;
}
- (void)onTap:(UITapGestureRecognizer *)sender
{
NSLog(@"add character");
UIImage * uiImg = [UIImage imageNamed:@"sel.png"];
CGPoint loc = [sender locationInView:self.view];
UIImageView * character = [[UIImageView alloc] initWithImage:uiImg];
character.center = loc;
[self.view addSubview:character];
}