2015-06-22 4 views
9

Как вы обнаружите и запустите действие при касании UIImageView? Это код, который я до сих пор:Обнаружение UIImageView Touch в Swift

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    var touch: UITouch = UITouch() 
    if touch.view == profileImage { 
     println("image touched") 
    } 
} 
+2

Убедитесь, что 'userInteractionEnabled' установлен в' true'. Я считаю, что это 'false' по умолчанию для' UIImageView'. – AdamPro13

+0

@ AdamPro13 все еще не работает с кодом, который у меня выше. –

ответ

17

Вы можете положить UITapGestureRecognizer внутри вашего UIImageView с помощью Interface Builder или в коде (как вы хотите), я предпочитаю первое. Затем вы можете поместить @IBAction и отрегулировать кран внутри вашего UIImageView. Не забудьте установить UserInteractionEnabled в true в Interface Builder или в код.

@IBAction func imageTapped(sender: AnyObject) { 
    println("Image Tapped.") 
} 

Надеюсь, это поможет вам.

13

Хорошо, я получил эту работу, вот что вы должны сделать:

@IBOutlet weak var profileImage: UIImageView! 
let recognizer = UITapGestureRecognizer() 

Создайте метод, чтобы сказать вам, когда изображение было похлопал

func profileImageHasBeenTapped(){ 
    println("image tapped") 
} 

Большой , теперь в вашем методе viewDidLoad напишите три другие строки кода, чтобы получить эту работу

override func viewDidLoad() { 
    super.viewDidLoad() 
    //sets the user interaction to true, so we can actually track when the image has been tapped 
    profileImage.userInteractionEnabled = true 

    //this is where we add the target, since our method to track the taps is in this class 
    //we can just type "self", and then put our method name in quotes for the action parameter 
    recognizer.addTarget(self, action: "profileImageHasBeenTapped") 

    //finally, this is where we add the gesture recognizer, so it actually functions correctly 
    profileImage.addGestureRecognizer(recognizer) 

} 
2

Swift 3

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    let touch:UITouch = touches.first! 
     if touch.view == profileImage { 
    println("image touched") 
} 

} 


override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    let touch:UITouch = touches.first! 
     if touch.view == profileImage { 
    println("image released") 
} 

} 
Смежные вопросы