我使用UITapGestureRecognizer将事件附加到UIImageViews

  override func viewDidLoad() {
    super.viewDidLoad()

    let cupPicture1Tap = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
    cupPicture1.userInteractionEnabled = true
    cupPicture1.addGestureRecognizer(cupPicture1Tap)
    let cupPicture2Tap = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
    cupPicture2.userInteractionEnabled = true
    cupPicture2.addGestureRecognizer(cupPicture2Tap)
    let cupPicture3Tap = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
    cupPicture3.userInteractionEnabled = true
    cupPicture3.addGestureRecognizer(cupPicture3Tap)
  }

  func cupImageTapped(recognizer:UIPanGestureRecognizer) {
    var clickedImageView: UIImageView = recognizer.view

    let myPickerController = UIImagePickerController()
    myPickerController.delegate = self;
    myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
    myPickerController.allowsEditing = true
    self.presentViewController(myPickerController, animated: true, completion: nil)
  }

但是我无法访问在cupImageTapped函数上单击的UIImageView。我得到:“无法转换'UIView类型的值?”到指定的类型'UIImageView'“

最佳答案

@IBOutlet var imageView: UIImageView!
@IBOutlet var MyImageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    // create tap gesture recognizer
    let tapGesture = UITapGestureRecognizer(target: self, action: "tapGesture:")

    // add it to the image view;
    imageView.addGestureRecognizer(tapGesture)
    // make sure imageView can be interacted with by user
    imageView.userInteractionEnabled = true
}

func tapGesture(gesture: UIGestureRecognizer) {
    // if the tapped view is a UIImageView then set it to imageview
    if let imageView = gesture.view as? UIImageView {  // if you subclass UIImageView, then change "UIImageView" to your subclass
        // change the image on the MyImageView
        MyImageView.image = imageView.image
        // if you subclass UIImageView, then you could get the filename here.
    }
}

这会工作

10-08 05:57