UITapGestureRecogniser无法正常工作

时间:2016-10-11 10:15:52

标签: ios swift uitapgesturerecognizer

我编写了与Apple文档中相同的代码,但是当我点击照片时,照片库没有出现。点击手势识别器可能无法正常工作。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

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

    // MARK: Properties
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var photoImageView: UIImageView!

    //MARK: Actions
    @IBAction func setDefaultLabelText(sender: UIButton) {
        nameLabel.text = "default"
    }
    @IBAction func selectImageFromPhotoLibrary(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 = UIImagePickerControllerSourceType.PhotoLibrary

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

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

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        // Dismiss the picker if the user canceled.
        dismissViewControllerAnimated(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.
        photoImageView.image = selectedImage

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

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

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

}

1 个答案:

答案 0 :(得分:0)

检查一次是否为您的Imageview启用了userInteraction属性,默认情况下为false,我们需要手动启用,请执行

photoImageView.userInteractionEnabled = true

例如

override func viewDidLoad(){
{
    super.viewDidLoad()

    let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
    photoImageView.userInteractionEnabled = true
    photoImageView.addGestureRecognizer(tapGestureRecognizer)
}

调用你的方法

func imageTapped(img: AnyObject)
{
    // Your action 
}