How come the values are nil? - ios

I am passing data from one class to another, and I am receiving nil values when I breakpoint and look at the console.
This is the class with the values, and I want to pass these values to the class viewc
func viewControllerAtIndex(index: Int) -> viewc {
if ((self.namepage.count == 0) || (index >= self.namepage.count) {
return viewcard()
}
var vc: viewc = self.storyboard?.instantiateViewControllerWithIdentifier("ItemController") as! viewc
vc.imageFile = self.pageImages[index] //not nil
vc.cTitle = self.namepage[index] //not nil
vc.nTitle = self.numberpage[index] //not nil
vc.pageIndex = index
vc.getArray()
return vc
}
This class is the class I want to pass the data to.
class viewc: UIViewController{
var pageIndex: Int!
var cTitle: String!
var imageFile: String!
var nTitle: String!
#IBOutlet weak var imagen: UIImageView!
#IBOutlet weak var name: UILabel!
#IBOutlet weak var number: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
func getArray() {
self.imagen.image = UIImage(named: self.imageFile)//imageFile is nil
self.name.text = self.cTitle//cTitle is nil
self.number.text = self.nTitle//nTitle is nil
}
}

func viewControllerAtIndex(index: Int) -> ViewC {
var vc = self.storyboard?.instantiateViewControllerWithIdentifier("ItemController") as! ViewC
vc.imageFile = self.pageImages[index]
vc.cTitle = self.namepage[index]
vc.nTitle = self.numberpage[index]
vc.pageIndex = index
vc.testProperties()
return vc
}
class ViewC: UIViewController{
var pageIndex: Int!
var cTitle: String!
var imageFile: String!
var nTitle: String!
#IBOutlet weak var imagen: UIImageView!
#IBOutlet weak var name: UILabel!
#IBOutlet weak var number: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
imagen.image = UIImage(named: imageFile)
name.text = cTitle
number.text = nTitle
}
// This will crash if one of them is nil
func testProperties() {
print("pageIndex: \(pageIndex)")
print("cTitle: \(cTitle)")
print("imageFile: \(imageFile)")
print("nTitle: \(nTitle)")
}
}
Now your ViewC will be set up properly. Notice you can only access your IBOutlet after the view has loaded. If you need to access the outlets before the view has loaded, you'll need to do something else.

The function should look like this.
func viewControllerAtIndex(index: Int) -> UIViewController?
{
let vc = storyboard?.instantiateViewControllerWithIdentifier (pagesArray[index]) return vc
}

Related

Passing Firebase Data from one view controller to detail view controller

I am looking to load data from my Firebase Database into a tableview in my main view controller and then pass that data to be more descriptive to a second view controller as my detail view controller. I am getting stuck because when i do click on the cell it will not segue to my other view controller and I am not sure how to get the data to pass. I want just the name on the first view controller and then the other data to populate on the detail view controller.
My Main View Controller--
import UIKit
import Foundation
import Firebase
import FirebaseDatabase
class ViewController: UIViewController {
var table = [FacStaffInfo]()
var ref: DatabaseReference!
#IBOutlet weak var Tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
ref = Database.database().reference().child("users")
ref.observe(DataEventType.value, with: {(snapshot) in
if snapshot.childrenCount > 0 {
self.table.removeAll()
for user in snapshot.children.allObjects as! [DataSnapshot] {
let object = user.value as? [String: AnyObject]
let title = object?["title"]
let name = object?["name"]
let email = object?["email"]
let phone = object?["phone"]
let office = object?["office"]
let bio = object?["bio"]
let user = FacStaffInfo(title: title as! String, name: name as! String, email: email as! String, phone: phone as! Int, office: office as! String, bio: bio as! String)
self.table.append(user)
self.Tableview.reloadData()
}
}
})
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return table.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell") as! TableViewCell
let user: FacStaffInfo
user = table[indexPath.row]
cell.titleLabel?.text = user.title
cell.nameLabel?.text = user.name
cell.emailLabel?.text = user.email
cell.phoneLabel?.text = String(user.phone)
cell.officeLabel?.text = user.office
cell.bioLabel?.text = user.bio
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetail", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = Tableview.indexPathForSelectedRow {
let destinationController = segue.destination as! InfoViewController
destinationController.FacStaffData = [table[indexPath.row]]
}
}
}
}
My Detail View controller--
import UIKit
import Firebase
import FirebaseDatabase
class InfoViewController: UIViewController {
var FacStaffData = [FacStaffInfo]()
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var emailLabel: UILabel!
#IBOutlet weak var phoneLabel: UILabel!
#IBOutlet weak var officeLabel: UILabel!
#IBOutlet weak var bioLabel: UILabel!
//var title = ""
var name = ""
var email = ""
var phone = ""
var office = ""
var bio = ""
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = title
nameLabel.text = name
emailLabel.text = email
phoneLabel.text = phone
officeLabel.text = office
bioLabel.text = bio
print(titleLabel)
}
}
My info class--
import Foundation
import Firebase
import FirebaseDatabase
class FacStaffInfo {
var title: String
var name: String
var email: String
var phone: Int
var office: String
var bio: String
init(title: String, name: String, email: String, phone: Int, office: String, bio: String) {
self.title = title;
self.name = name;
self.email = email;
self.phone = phone;
self.office = office;
self.bio = bio
}
}
and my tableview cell--
import UIKit
import Firebase
import FirebaseDatabase
class TableViewCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var emailLabel: UILabel!
#IBOutlet weak var phoneLabel: UILabel!
#IBOutlet weak var officeLabel: UILabel!
#IBOutlet weak var bioLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
It looks like didSelectRowAt just implements didSelectRowAt again without calling anything.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetail", sender: self)
}
}
try again with:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetail", sender: self)
}
Updated for followup:
The InfoViewController is using the default values. When you prepare the segue, you put the information into FacStaffData. This should do the trick.
class InfoViewController: UIViewController {
var FacStaffData = [FacStaffInfo]()
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var emailLabel: UILabel!
#IBOutlet weak var phoneLabel: UILabel!
#IBOutlet weak var officeLabel: UILabel!
#IBOutlet weak var bioLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = FacStaffData.title
nameLabel.text = FacStaffData.name
emailLabel.text = FacStaffData.email
phoneLabel.text = FacStaffData.phone
officeLabel.text = FacStaffData.office
bioLabel.text = FacStaffData.bio
print(titleLabel)
}
}

Why i only see the last element of array in a table view in swift 5?

I have a UI as given below and when i click save button in UI i want to add three values on top of the view to a table view, in which has three different labels for representing them and a custom structure to define the model. But my problem is that i can only append one element but what i want is to keep previously added elements in that array and show them in a tableView.
Here is the UI image
Here is the code:
MainViewController.swift
class MainViewController: UIViewController {
#IBOutlet weak var minDbLabel: UILabel!
#IBOutlet weak var averageDbLabel: UILabel!
#IBOutlet weak var maximumDbLabel: UILabel!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "saveRecord" {
let recordVC = segue.destination as! RecordTableViewController
recordVC.record.minimumValue = (minDbLabel.text! as NSString).floatValue
recordVC.record.averageValue = (averageDbLabel.text! as NSString).floatValue
recordVC.record.maximumValue = (maximumDbLabel.text! as NSString).floatValue
recordVC.recordsArray.append(recordVC.record)
}
}
#IBAction func save(_ sender: UIButton){
self.performSegue(withIdentifier: "saveRecord", sender: nil)
}
}
RecordTableViewController.swift:
class RecordCell: UITableViewCell {
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var minimumValueLabel: UILabel!
#IBOutlet weak var averageValueLabel: UILabel!
#IBOutlet weak var maximumValueLabel: UILabel!
}
class RecordTableViewController: UITableViewController {
let cellIdentifier: String = "cellID"
var recordsArray = [Record]()
var record: Record = Record()
override var shouldAutorotate: Bool {
return false
}
override func viewDidLoad() {
super.viewDidLoad()
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeRight(_:)))
swipe.direction = .right
self.view.addGestureRecognizer(swipe)
tableView.insertRows(at: [IndexPath(row: recordsArray.count - 1, section: 0)], with: .automatic)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recordsArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RecordCell
cell.minimumValueLabel.text = "\(recordsArray[indexPath.row].minimumValue)"
cell.averageValueLabel.text = "\(recordsArray[indexPath.row].averageValue)"
cell.maximumValueLabel.text = "\(recordsArray[indexPath.row].maximumValue)"
return cell
}
}
Record.swift
struct Record {
var minimumValue: Float = .nan
var averageValue: Float = .nan
var maximumValue: Float = .nan
}
Thanks in advance.
Note: I already have searched on Google to find an answer but to no avail.
you should append the data in recordsArray in MainViewController first before performing the segue. See the code below
class MainViewController: UIViewController {
#IBOutlet weak var minDbLabel: UILabel!
#IBOutlet weak var averageDbLabel: UILabel!
#IBOutlet weak var maximumDbLabel: UILabel!
var recordsArray = [Record]()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "saveRecord" {
let recordVC = segue.destination as! RecordTableViewController
var record = Record()
record.minimumValue = Float(minDbLabel.text!) ?? 0.0
record.averageValue = Float(averageDbLabel.text!) ?? 0.0
record.maximumValue = Float(maximumDbLabel.text!) ?? 0.0
self.recordsArray.append(record)
recordVC.recordsArray = self.recordsArray
}
}
#IBAction func save(_ sender: UIButton){
self.performSegue(withIdentifier: "saveRecord", sender: nil)
}
}
Just replace your MainViewController with the code above and it should work.

Transferring data from a UITableViewCell cocoa touch class to a UIViewController class

Okay, so what I am essentially trying to do is transfer data from a UITableViewCell class to a UIViewController class. Below is my UITableViewCell:
class OrderCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
}
var post: OrderModel!
var link: Link!
var addedList: [String:Float] = [:]
#IBOutlet weak var dishName: UILabel!
#IBOutlet weak var dishDescriptionAndPrice: UILabel!
#IBOutlet weak var numberOfOrders: UILabel!
#IBOutlet weak var addOrderBtn: UIButton!
#IBOutlet weak var subtractOderBtn: UIButton!
#IBAction func addButtonPressed(sender: AnyObject) {
if numberOfOrders.text == "9" {
numberOfOrders.text = "9"
} else {
numberOfOrders.text = String((Int(numberOfOrders.text!)! + 1))
}
addedList.updateValue(post.dishPrice, forKey: post.dishName)
print(addedList)
}
#IBAction func subtractButtonPressed(sender: AnyObject) {
if numberOfOrders.text == "0" {
numberOfOrders.text = "0"
} else {
numberOfOrders.text = String((Int(numberOfOrders.text!)! - 1))
}
}
func getOrders() -> Dictionary<String, Float> {
return addedList
}
func configureCell(post: OrderModel) {
self.post = post
self.dishName.text = post.dishName
self.dishDescriptionAndPrice.text = post.dishDescription
self.numberOfOrders.text = "0"
}
}
What I am trying to do, is have my other class (which is of UIViewController), retrieve 'addedList' from the above class. I obviously cannot use prepareForSegue, and I have had no luck find a way to do this that is compatible with these two classes. I am open to creating a new class to be the "bridge" between the two and transfer the data through, but I again cannot find a way to do this. Any and all help is greatly appreciated, thank you in advance.
To get more specific, the UIViewController holds my tableview, and the class that is above is just the object file for each individual cell. I need to transfer the data when the addButtonPressed IBaction is called.
You can do this by creating a delegate in your cell class. And in your view controller class, under cell for row at indexPath, add:
cell.delegate = self
And update your cell class like this:
protocol ClassNameDelegate:class {
func addButtonAction(addedList:[String:Float])
}
#IBOutlet weak var dishName: UILabel!
#IBOutlet weak var dishDescriptionAndPrice: UILabel!
#IBOutlet weak var numberOfOrders: UILabel!
#IBOutlet weak var addOrderBtn: UIButton!
#IBOutlet weak var subtractOderBtn: UIButton!
//Create a delegate
weak var delegate: ClassNameDelegate?
#IBAction func addButtonPressed(sender: AnyObject) {
if numberOfOrders.text == "9" {
numberOfOrders.text = "9"
} else {
numberOfOrders.text = String((Int(numberOfOrders.text!)! + 1))
}
addedList.updateValue(post.dishPrice, forKey: post.dishName)
print(addedList)
// Call this when added list is done and get the call to your view controller.
if delegate != nil {
delegate?.addButtonAction(addedList: addedList)
}
}
#IBAction func subtractButtonPressed(sender: AnyObject) {
if numberOfOrders.text == "0" {
numberOfOrders.text = "0"
} else {
numberOfOrders.text = String((Int(numberOfOrders.text!)! - 1))
}
}
func getOrders() -> Dictionary<String, Float> {
return addedList
}
func configureCell(post: OrderModel) {
self.post = post
self.dishName.text = post.dishName
self.dishDescriptionAndPrice.text = post.dishDescription
self.numberOfOrders.text = "0"
}
}
Finally import this delegate method in your view controller class, in the same way you import tableView delegate and datasource.
A cell is not the good place to store information like this. You should store the information in your view controller. And when your cell button is pressed, retrieve the information thanks to the index path of the cell.
In your cell:
func configureCell(post: OrderModel, delegate:UIViewController) {
self.dishName.text = post.dishName
self.dishDescriptionAndPrice.text = post.dishDescription
self.numberOfOrders.text = "0"
self.addButton.addTarget(delegate, action: #selector(delegate.addButtonPressed(_:)), for: UIControlEvents.touchUpInside)
}
In your view controller:
//store your data in your view controller
var data=[OrderModel]()
func addButtonPressed(_ button:UIButton){
let selectedCell=button.superview?.superview? as! OrderCell
let indexPath=tableView.indexPath(for: selectedCell)
let cellData=data[indexPath!.row]
if cellData.numberOfOrders==9{
selectedCell.numberOfOrders.text="9"
}else{
selectedCell.numberOfOrders.text=String(cellData.numberOfOrders+1)
}
}

Swift delegate not working

I have a stepper in my ViewController that controls the value of a variable in my UIView. When I reset the variables to 0 in my UIView, I also want the stepper and label to reset, but they won't. I tried using a delegate, but am getting an error. Thanks in advance!
ViewController:
protocol CircleViewDelegate: class {
func updateStepper(view: CircleView)
}
class ViewController: UIViewController, CircleViewDelegate {
var colors = CircleView()
#IBOutlet weak var circleView1: CircleView!
#IBOutlet weak var blueStepper: UIStepper!
#IBOutlet weak var greenStepper: UIStepper!
#IBOutlet weak var redStepper: UIStepper!
#IBOutlet weak var redValue: UILabel!
#IBOutlet weak var greenValue: UILabel!
#IBOutlet weak var blueValue: UILabel!
var circleViewDelegate: CircleView!
override func viewDidLoad() {
super.viewDidLoad()
circleViewDelegate!.delegate = self
}
func updateStepper(view: CircleView) {
redStepper.value=0.0;
greenStepper.value=0.0;
blueStepper.value=0.0;
}
#IBAction func stepperChange(sender: UIStepper) {
circleView1.redd1 = Int(redStepper.value);
redValue.text = Int(sender.value).description;
}
#IBAction func stepperChange1(sender: UIStepper) {
circleView1.greenn1 = Int(greenStepper.value);
greenValue.text = Int(sender.value).description;
}
#IBAction func stepperChange2(sender: UIStepper) {
circleView1.bluee1 = Int(blueStepper.value);
blueValue.text = Int(sender.value).description;
}
}
UIView:
class CircleView: UIView {
var redd1 = 0
var greenn1 = 0
var bluee1 = 0
weak var delegate: CircleViewDelegate?
func updateStepper() {
delegate?.updateStepper(self)
}
func game() {
if(redd1==Int(red1) && greenn1==Int(green1) && bluee1==Int(blue1)) {
redd1 = 0;
green1 = 0;
blue1 = 0;
updateStepper()
}
}
}
Try this:
override func viewDidLoad() {
super.viewDidLoad()
circleView1.delegate = self
}
func updateStepper(view: CircleView) {
redStepper.value = 0.0
greenStepper.value = 0.0
blueStepper.value = 0.0
stepperChange(redStepper)
stepperChange(greenStepper)
stepperChange(blueStepper)
}
Instead of assigning the delegate like this circleViewDelegate!.delegate = self in viewDidLoad try circleView1.delegate = self

swift 2 How can click on a specific image that in array, to move into another page that already exist

I have three page:-
first page:- ViewController
import UIKit
class ViewController: UIViewController, UIPageViewControllerDataSource {
var pageViewController: UIPageViewController!
var pageTitles: NSArray!
var pageImages: NSArray!
var pageImages1: NSArray!
var pageImages2: NSArray!
var pageImages3: NSArray!
var pageImages4: NSArray!
var pageImages5: NSArray!
override func viewDidLoad() {
super.viewDidLoad()
self.pageTitles = NSArray(objects: "A","B","C")
self.pageImages = NSArray(objects: "clashs","wizard","archer")
self.pageImages1 = NSArray(objects: "wizard","archer","clashs")
self.pageImages2 = NSArray(objects: "clashs","wizard","archer")
self.pageImages3 = NSArray(objects: "clashs","wizard","archer")
self.pageImages4 = NSArray(objects: "clashs","wizard","archer")
self.pageImages5 = NSArray(objects: "clashs","wizard","archer")
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
var startVC = self.viewControllerAtIndex(0) as ContentViewController
var viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: true, completion:nil )
self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.size.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func restartAction(sender: AnyObject) {
var startVC = self.viewControllerAtIndex(0) as ContentViewController
var viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: true, completion: nil)
}
func viewControllerAtIndex(index: Int) -> ContentViewController
{
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count))
{
return ContentViewController()
}
var vc: ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as!
ContentViewController
vc.imageFile = self.pageImages[index] as! String
vc.imageFile1 = self.pageImages1[index] as! String
vc.imageFile2 = self.pageImages2[index] as! String
vc.imageFile3 = self.pageImages3[index] as! String
vc.imageFile4 = self.pageImages4[index] as! String
vc.imageFile5 = self.pageImages5[index] as! String
vc.titleText = self.pageTitles[index] as! String
vc.pageIndex = index
return vc
}
//Musab:- page view controller data source
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == 0 || index == NSNotFound)
{
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == NSNotFound)
{
return nil
}
index++
if (index == self.pageTitles.count)
{
return nil
}
return self.viewControllerAtIndex(index)
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return self.pageTitles.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
second page:- SecondController
import UIKit
class SeconfViewController: UIViewController {
var detailImages: Array<UIImage>?
#IBOutlet weak var label1: UILabel!
#IBOutlet var background: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Third page:- ContentViewController
import UIKit
class ContentViewController: UIViewController {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var imageView1: UIImageView!
#IBOutlet weak var imageView2: UIImageView!
#IBOutlet weak var imageView3: UIImageView!
#IBOutlet weak var imageView4: UIImageView!
#IBOutlet weak var imageView5: UIImageView!
var pageIndex: Int!
var titleText: String!
var imageFile: String!
var imageFile1: String!
var imageFile2: String!
var imageFile3: String!
var imageFile4: String!
var imageFile5: String!
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.image = UIImage(named:self.imageFile)
self.imageView1.image = UIImage(named:self.imageFile1)
self.imageView2.image = UIImage(named:self.imageFile2)
self.imageView3.image = UIImage(named:self.imageFile3)
self.imageView4.image = UIImage(named:self.imageFile4)
self.imageView5.image = UIImage(named:self.imageFile5)
self.titleLabel.text = self.titleText
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
now, when i clicking on a specific image, i want to move into second page
example:- when i clicking on a "clashs" image, i want to go (SecondViewController).
please, any one help me?
You are more or less asking how to do some action on taps?
Here's an answer for that: How to assign an action for UIImageView object in Swift
And once the user has tapped:
self.navigationController?.pushViewController(SecondViewController(), animated: true)
Assuming you have a navigation controller.
you can add tap gesture on Image and set target .
self.imgView.userInteractionEnabled = true
let imgTapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
imgTapGesture.numberOfTapsRequired = 1
self.imgView.addGestureRecognizer(imgTapGesture)
And in target method whatever you want you can do.
func imageTapped(sender:UITapGestureRecognizer) ->Void
{
}

Resources