swift 中 UIImageView 上的 UITapGestureRecognizer 操作

UITapGestureRecognizer Action on UIImageView in swift

我正在努力找出我的 UITapGestureRecognizer 出了什么问题,我在操作的开头放置了断点,但它从未被调用过。我正在按照此处显示的示例进行操作。

https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson4.html

我将 UIImageView 连接到像这样的点击手势。

然后我像这样设置了 UITapGestureRecognizer。

最后,我的代码几乎与演示中的代码完全相同。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{

//MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!
@IBOutlet weak var imagePhotoControl: UIImageView!



override func viewDidLoad() {
    super.viewDidLoad()
    nameTextField.delegate = self;

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder();
    return true;
}


func textFieldDidEndEditing(textField: UITextField) {
    mealNameLabel.text = textField.text;
}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    // Dismiss the picker if the user canceled.
    dismissViewControllerAnimated(true, completion: nil)
}
 // MARK: Actions
@IBAction func selectImageFromLibraryAlso(sender: UITapGestureRecognizer) {
    // Hide the keyboard.
    nameTextField.resignFirstResponder()

    // UIImagePickerController is a view controller that lets a user pick media from their photo library.
    let imagePickerController = UIImagePickerController()

    // Only allow photos to be picked, not taken.
    imagePickerController.sourceType = .PhotoLibrary

    // Make sure ViewController is notified when the user picks an image.
    imagePickerController.delegate = self

    presentViewController(imagePickerController, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    // The info dictionary contains multiple representations of the image, and this uses the original.
    let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    // Set photoImageView to display the selected image.
    imagePhotoControl.image = selectedImage

    // Dismiss the picker.
    dismissViewControllerAnimated(true, completion: nil)
}


@IBAction func setDefaultLabelText(sender: UIButton) {
    mealNameLabel.text = "Default Text"
 }
}

我只是不明白为什么当我点击图片时永远不会触发该操作。我什至下载了演示代码,并且按预期工作。我确实用 space 命名了我的项目 Food Tracker,这会是问题所在吗?我基本上把自己逼疯了,试图弄清楚为什么事件没有被解雇。我准备好在我的项目和演示项目之间进行文件夹差异。

回答内容: 所以事实证明,属性检查器中的 UIImageView 上有一个名为“启用用户交互”的复选框。如果您选中此项,它将允许从您的 UITapGestureRecognizer 触发触摸事件。另一种解决方案是按照下面的答案中所述在代码中执行此操作。

//在ViewDidLoad中设置

imagePhotoControl.userInteractionEnabled = true ;