get the clicked imageview swift

1.5k Views Asked by At

I want to know which imageview was clicked by the user I am using the following code, but it is not calling the leftTapView and rightTapView functions

class CustomTableViewCell : UITableViewCell {
    @IBOutlet var leftTeamImage: UIImageView!
    @IBOutlet var rightTeamImage: UIImageView!
    @IBOutlet var rightTeamNameLabel: UILabel!
    @IBOutlet var leftTeamNameLabel: UILabel!
    @IBOutlet var leftTeamScoreLabel: UILabel!
    @IBOutlet var rightTeamScoreLabel: UILabel!


    @IBOutlet var leftView : UIView!
    @IBOutlet var rightView : UIView!

    let lettTapRec = UITapGestureRecognizer()
    let rightTapRec = UITapGestureRecognizer()

    ScoreLabel.text = leftTeamScore
        rightTeamNameLabel.text = rightTeamName.uppercaseString
        rightTeamScoreLabel.text = rightTeamScore
    }
    func load(#leftTeamName: String, rightTeamName: String, leftTeamScore: Int, rightTeamScore: Int) {

        leftTeamNameLabel.text = leftTeamName.uppercaseString
        leftTeamScoreLabel.text = String(leftTeamScore)
        rightTeamNameLabel.text = rightTeamName.uppercaseString
        rightTeamScoreLabel.text = String(rightTeamScore)



lettTapRec.addTarget(self, action: "leftTapView")
        leftView.userInteractionEnabled = true
        leftView.addGestureRecognizer(lettTapRec)
        //
        rightTapRec.addTarget(self, action: "rightTapView")
        rightView.userInteractionEnabled = true
        rightView.addGestureRecognizer(rightTapRec)
    }



    func leftTapView(sender: AnyObject){
        println("left")
    }
    func rightTapView(sender: AnyObject){
        println("left")
    }
}

protocol ImageTappedProtocols {
    func leftImageTapped(imageView : UIImage)
    func rightImageTapped(imageView: UIImage)
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate  {

    @IBOutlet var tableView : UITableView!

    var items: [(String, String)] = [
        ("My", "swift 1.jpeg"),
        ("Name", "swift 2.jpeg"),
        ("is", "swift 3.jpeg"),
        ("Atif", "swift 4.jpeg"),
        ("Farrukh", "swift 5.jpeg")
    ]
    var team1 :[String] = []
    var team2 :[String] = []
    var id : [String] = []
    var team1_bets : [Int] = []
    var team2_bets : [Int] = []
    var end_date : [String] = []

    var list = Dictionary<String, String>()
    var count : Int = 0

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return count;
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell

        // this is how you extract values from a tuple
        var (title, image) = items[indexPath.row]
        var teama: String = team1[indexPath.row]
        var teamb: String = team2[indexPath.row]
        var teamAScore : Int  = team1_bets[indexPath.row]
        var teamBScore : Int  = team2_bets[indexPath.row]

        cell.backgroundColor = UIColor(red: 123, green: 225, blue: 38, alpha: 0.2)

        return cell
    }

    func tableView(tableView : UITableView, didSelectedRowAtIndexPath indexPath : NSIndexPath){
        //tableView.deselectRowAtIndexPath(indexPath, animated: true)
        println("You selected cell #\(indexPath.row)!")
        let indexPath = tableView.indexPathForSelectedRow();

        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

        println(currentCell.textLabel.text)
    }
    func tableView(tableView : UITableView, didSelectRowAtIndexPath indexPath : NSIndexPath){
        //tableView.deselectRowAtIndexPath(indexPath, animated: true)
        println("You selected cell #\(indexPath.row)!")
        let indexPath = tableView.indexPathForSelectedRow();

        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!

        println(currentCell.contentView)
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let urlAsString = "http://codespikestudios.com/betting_app/bet/get_events/1"
        //let urlAsString = "http://api.topcoder.com/v2/challenges?pageSize=2"
        let url: NSURL  = NSURL(string: urlAsString)!
        let urlSession = NSURLSession.sharedSession()

        //2
        let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
            if (error != nil) {
                println(error.localizedDescription)
            }
            var err: NSError?

            // 3
            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSArray
            if (err != nil) {
                println("JSON Error \(err!.localizedDescription)")
            }

            // 4
            println(jsonResult)
            println(jsonResult.count)
            println(jsonResult[1].valueForKey("cat_name") as String)

            var dictionary = Dictionary<String, String>()

            self.count = jsonResult.count
            for var i = 0; i < self.count; i++ {


                self.team1 = jsonResult.valueForKey("team1") as Array
                self.team2 = jsonResult.valueForKey("team2") as Array
                self.team1_bets = jsonResult.valueForKey("team1_bets") as Array
                self.team2_bets = jsonResult.valueForKey("team2_bets") as Array

            }
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.tableView.reloadData()
            })
            //let jsonDate: String! = jsonResult["date"] as NSString
            //let jsonTime: String! = jsonResult["time"] as NSString

            //println(jsonTime)
        })
        // 5
        jsonQuery.resume()


        var nib = UINib(nibName: "MyTableViewCell", bundle: nil)

        tableView.registerNib(nib, forCellReuseIdentifier: "customCell")

    }

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


}

this is all I get

You selected cell #3!
<UITableViewCellContentView: 0x7f871b687350; frame = (0 0; 580 136.5); opaque = NO; gestureRecognizers = <NSArray: 0x7f871b68c180>; layer = <CALayer: 0x7f871b687420>>
3

There are 3 best solutions below

0
On BEST ANSWER

A view with an alpha of 0.0 won't receive touch events.

From the Event Handling guide:

"Note that a view also does not receive touch events if it’s hidden or transparent."

From the Creating Views documentation:

"A hidden view does not receive touch events from the system."

3
On

You will want to add a target when you initialize your gesture recognizers. That would look like, for instance:

let leftTapRect = UIGestureRecognizer(target: self, action: "leftTapView:")

In addition, you will need to add a sender argument to your event handlers leftTapView and rightTapView:

func leftTapView(sender: AnyObject) {
    ...
}
0
On

solved my problem, Actually i had set my view's alpha to 0, when I set it to 1 and made the set the background as Clear Colour it started working. Rest the working perfectly. If someone can explain the reason of why setting alpha doesnt trigger the tap gesture I will gladly accept hi/her answer as accepted.