是否可以循环在图像上创建轻击手势?

时间:2013-06-13 03:10:02

标签: iphone objective-c uiimageview uitapgesturerecognizer

我在scrollVIew上有循环创建图像,我需要在点击每个图像时控制动作。我听说可以在图像上设置点按手势,但我不知道如何通过循环将点击手势设置为我之前创建的图像。是否可以在循环中的每个图像上创建点击手势?怎么样?

2 个答案:

答案 0 :(得分:0)

试试这个

for(int i=0;i<20;i++)
{
  UIImageView *img=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"yourimage.png"]];
 [img setTag:i];
 img.frame= //set frame accordingly;
  img.userInteractionEnabled = YES;
  UITapGestureRecognizer *tap =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[img addGestureRecognizer:tap];
[tap release];
[scrollView addSubView:img];

}

- (void)handleTap:(UITapGestureRecognizer *)recognizer  {
    UIImageView *imageView = (UIImageView *)recognizer.view;

      switch([imageView tag])
    {
       case 1:
          //do your work
          break;
       .
       .
       .
       .
       case n:

    }
}

答案 1 :(得分:0)

Swift中的功能相同,

@IBOutlet weak var img1: UIImageView!
@IBOutlet weak var img2: UIImageView!
@IBOutlet weak var img3: UIImageView!
let imgs = [img1, img2, img3]

for (index, img) in images.enumerated() {
 img.tag = index
 let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
 img.isUserInteractionEnabled = true
 img.addGestureRecognizer(tapGesture)
}


@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer){
        let img : UIImageView = tapGestureRecognizer.view as! UIImageView
        switch(img.tag) {
        {
          case 0:
           //your code
           break;

           ...
        }
}

希望这有助于某人。