简体   繁体   English

在UI表格视图单元格中单击获取图像

[英]Get image click inside UI table view cell

i tried to add gesture recognizer in my UIImageView 我试图在我的UIImageView中添加手势识别器

 let rc = UITapGestureRecognizer(target: self, action: "foo:")
 rc.numberOfTapsRequired = 1
 rc.numberOfTouchesRequired = 1
 cell.bar.tag = indexPath.row
 cell.bar.addGestureRecognizer(rc)

but didn't call my foo function 但没有叫我的foo功能

func foo(sender: UIImageView! ) {
    self.performSegueWithIdentifier("VC", sender: sender)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "VC" {
        let vc = segue.destinationViewController as! VC
        vc.item = items[sender.tag]
    }
}

So, as I mentioned before your problem is UIImageView by default has property userInteractionEnabled set to false . 所以,正如我之前提到的,你的问题是UIImageView默认情况下将属性userInteractionEnabled设置为false You can change this in you storyboard, or add line cell.bar.userInteractionEnabled = true . 您可以在故事板中更改此设置,或添加行cell.bar.userInteractionEnabled = true

Next your problem is in your foo: method implementation: you specify sender as UIImageView! 接下来你的问题出在你的foo:方法实现中:你将发送者指定为UIImageView! , but it should be UITapGestureRecognizer . ,但它应该是UITapGestureRecognizer This is why it crashes - it cannot be UIImageView , so when it unwraps ( ! ) it is nil . 这就是为什么它崩溃 - 它不能是UIImageView ,所以当它解开( ! )时它是nil

Solution: change your foo method declaration to foo(recognizer: UITapGestureRecognizer) . 解决方案:将您的foo方法声明更改为foo(recognizer: UITapGestureRecognizer) If you need access your imageView inside this method you can use code below: 如果您需要在此方法中访问imageView ,可以使用以下代码:

if let imageView = recognizer.view as? UIImageView {
  ...
}

or with new guard keyword (Swift 2.0) 或者使用新的guard关键字(Swift 2.0)

guard let imageView = recognizer.view as? UIImageView
else { return }
...

You can change 你可以改变

foo(recognizer: UITapGestureRecognizer) {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM