试试下面的代码:
import UIKit
class SignUpViewController: UIViewController, UIImagePickerControllerDelegate {
@IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
}
func imageTapped(gesture:UIGestureRecognizer) {
if let profile1Pic = gesture.view as? UIImageView {
print("Image Tapped")
showActionSheet()
}
}
func camera()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func photoLibrary()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func showActionSheet() {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
profilePic.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
}
它在我身边工作..希望能为你做一些!