6

私はいくつかのUIImageViewを持っており、それぞれにタグがあります。画像の配列があります。ユーザーがUIImageViewの1つをタップすると、アプリは配列から特定の画像を返します。

私はこのように実装します:

- (void)viewDidLoad 
{
    [super viewDidLoad];
    scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [self.view addSubview:scroll];

    NSInteger i;
    for (i=0; i<8; i++) 
    {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, i*100 + i*15, 300, 100)];
        imageView.backgroundColor = [UIColor blueColor];
        imageView.userInteractionEnabled = YES;
        imageView.tag = i;

        NSLog(@"%d", imageView.tag);

        [scroll addSubview:imageView];

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(findOutTheTag:)];
        [imageView addGestureRecognizer:tap];

    }

    scroll.contentSize = CGSizeMake(320, 115*i);

}
- (void)findOutTheTag:(id)sender
{

    //  HOW TO FIND THE tag OF THE imageView I'M TAPPING?

}

を見つけて、imageView.tagに渡しimageView.tagたい

UIImageView *tappedImage = [imageArray objectAtIndex:imageView.tag];

画像を表示します。

tagそれらすべてにタグを付けました。問題は、タップしているimageViewをどのように見つけることができるかということです。読んでくれてありがとう^_^

4

3 に答える 3

12

アプリの全体像を見ずに推奨を行うリスクがあるので、UIImageViewsの代わりにカスタムUIButtonを使用してみませんか?UIButtonを使用すると、アクションを設定して送信者IDを渡すことができます。このIDから、タグに簡単にアクセスして、配列からデータを取得できます。

または、上記のコードを本当に使用したいが、-(void)findOutTheTag:(id)senderメソッドが呼び出されていることを知っている場合は、次のことを行う必要があります。

- (void)findOutTheTag:(id)sender {
    switch (((UIGestureRecognizer *)sender).view.tag)      
{
    case kTag1:
    //...
    case kTag2:
    //...
  }
}
于 2010-12-13T00:54:13.817 に答える
2

UIImageViewを使用する代わりに、UIButtonを使用してみませんか。そうすれば、UITouchDownイベントのリスナーを簡単に追加できます。各ボタンにタグを付けて、touchDownメソッドでどのボタンが押されたかを確認できるようにすることができます。

    UIButton *button = [[UIImageView alloc] initWithFrame:CGRectMake(10, i*100 + i*15, 300, 100)];
    button.backgroundColor = [UIColor blueColor];
    button.tag = i;
    [button addTarget:self action:@selector(touchDown:) controlEvent:UIControlEventTouchDown]; 

また、touchDown:メソッドの内部では、タグにアクセスするために送信者をUIButtonにキャストするだけです。

- (void)touchDown:(id)sender
{
    UIButton* button = (UIButton*)sender;
    switch(button.tag)
    {
        case TAG1:
           break;
        //etc
    }
}
于 2010-12-13T01:03:23.690 に答える
1

タッチする必要のある画像を見つけるには、touchBeganメソッドを使用します。

注:まず、画像ビューについて確認する必要があります。次のuserIntrectionEnabled=YES; 方法を使用します。

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
    // get touch event
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
    if ([touch view].tag == 800) {

     //if image tag mated then perform this action      
    }
}

touchBegan内でswitchステートメントを使用できます。

于 2010-12-13T08:45:09.250 に答える