将图像添加到子类UIImageView

时间:2013-12-25 04:27:27

标签: ios objective-c uiviewcontroller uiimageview subclass

我正在尝试从子类UIImageView添加一个点击手势,然后从View Controller控制点击。我没有收到任何编译错误,但“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;
}

2 个答案:

答案 0 :(得分:0)

在您的子类imageView后面放置一个视图。将手势识别应用于新视图。 您可以从新视图控制点击手势。如果我不清楚,或者需要更多信息,请告诉我。

答案 1 :(得分:0)

我认为你想要的是......你想在用户点击屏幕时显示图像。 请执行以下步骤: 拖曳在视图控制器的默认视图中放置一个轻击手势识别器。 2.使用ViewController.m连接(ctrl +)gestureRecognizer

看看这段代码。 (刚刚修改了你的代码)

- (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];
}