UIImageView Touch Event - PullRequest
       30

UIImageView Touch Event

34 голосов
/ 23 сентября 2010

Я хочу вызвать событие нажатия моей кнопки, касаясь вида изображения uii, названного (image1). Вид изображения, помещенный в вид изображения uiview (вид1).

Это мой код:

- (IBAction)buttonClicked:(id)sender
{

 myTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(alphabutt:) userInfo:nil repeats:NO];
 }


-(IBAction)alphabutt:(id)sender
{
 NSLog(@"alphabutt!");


 if(i==1)
 {
  NSLog(@"i==1");
  [image1 setImage:[UIImage imageNamed:@"appleimg.jpg"]];
  [view1 addSubview:image1];  
  transition1 = [CATransition animation];

  transition1.duration = 0.75;

  transition1.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

  transition1.type=kCATransitionReveal;
  transition1.subtype=kCATransitionFromRight;
  transitioning = YES;
  transition1.delegate = self;
  [image1.layer addAnimation:transition1 forKey:nil];  
 }
 if(i==2)
 {
  NSLog(@"i==2");
  [image1 setImage:[UIImage imageNamed:@"boatimg.jpg"]];
  [view1 addSubview:image1];  
  transition2 = [CATransition animation];

  transition2.duration = 0.75;

  transition2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

  transition2.type=kCATransitionFade;
  transition2.subtype=kCATransitionFromRight;
  transitioning = YES;
  transition2.delegate = self;
  [image1.layer addAnimation:transition2 forKey:nil];

  i=0;
 }
i++;

}

Выше приведен мой код, при нажатии кнопки вызывается событие clickcliced. Внутри события buttonclick таймер работает для вызова alphabutt (событие нажатия кнопки) с интервалом времени 2.0. Alphabutt вызывается с каждым 2.0. чтобы сделать эту анимацию, когда я касаюсь uiimageview (изображение 1), только он вызывает событие нажатия кнопки (alphabutt). Как я могу написать сенсорное событие для просмотра изображений ...

Пожалуйста, кратко поясните код для выполнения события касания uiimageview ...

Ответы [ 4 ]

59 голосов
/ 06 сентября 2012

вы можете использовать UITapGestureRecognizer, добавленное к UIImageView через addGestureRecognizer

сниппеты:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bannerTapped:)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[iv addGestureRecognizer:singleTap];
[iv setUserInteractionEnabled:YES];

и

- (void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer {
    NSLog(@"%@", [gestureRecognizer view]);
}
56 голосов
/ 23 сентября 2010

Включите взаимодействие с пользователем для просмотра изображений в xib (или через код, если вы добавляете его программно) и используйте методы touchesBegan, touchesMoved, touchesEnded и т. Д. Для обнаружения касания в представлении изображения:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];

    if ([touch view] == yourImageView)
    {
            //add your code for image touch here 
    }

}
13 голосов
/ 12 марта 2015

Здесь я покажу вам две возможности для достижения этой цели в Swift :

Первая возможность

import UIKit

class ViewController: UIViewController {
    @IBOutlet var myUIImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // You can also manually set it through IB 
        // selecting the UIImageView in the storyboard
        // and checking "User Interaction Enabled" checkbox 
        // in the Attributes Inspector panel.
        self.myUIImageView.userInteractionEnabled = true
    }

    // You can choose to use one of the UIResponder methods:
    // touchesBegan, touchesMoved, touchesEnded etc, in order to detect the touch
    // on the UIImageView.
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
       let touch: UITouch? = touches.first
       if touch?.view == myUIImageView {
          println("myUIImageView has been tapped by the user.")
       }
       super.touchesEnded(touches, withEvent: event)
    }
}

Вторая возможность

import UIKit

class ViewController: UIViewController {
    @IBOutlet var myUIImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let singleTap = UITapGestureRecognizer(target: self, action: "myUIImageViewTapped:")
        singleTap.numberOfTapsRequired = 1 // Initialized to 1 by default
        singleTap.numberOfTouchesRequired = 1 // Initialized to 1 by default
        self.myUIImageView.addGestureRecognizer(singleTap)
        self.myUIImageView.userInteractionEnabled = true
    }

    func myUIImageViewTapped(recognizer: UITapGestureRecognizer) {
        if(recognizer.state == UIGestureRecognizerState.Ended){
            println("myUIImageView has been tapped by the user.")
        }
    }
}
6 голосов
/ 13 декабря 2012

Вы также можете перетащить объект UIButton поверх UIImageView.Затем в редакторе раскадровки просто сделайте тип UIButton типа Custom, сделав UIButton невидимым.Затем обработайте событие click так же, как и для любой кнопки.

...