Search code examples
iosswiftuitableviewviewwithtag

cell.contentView.viewWithTag gives nil value while loading data in UITableView


I am looking to captured image tap event on the first record of UITableView, when user taps I cell.imageAvtar I just want to capture that event.

This is the code I am using

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
                let cell = tableView.dequeueReusableCellWithIdentifier("details", forIndexPath: indexPath) as! AccountCell
                if (indexPath.row == 0) {
    (cell.contentView.viewWithTag(101) as! UIImageView).image = UIImage(named: "no_image_available.jpg")
    }
return cell
}

But (cell.contentView.viewWithTag(101) is returning as nil.I have tried (cell.contentView.viewWithTag(100) tried (cell. imageAvtar.viewWithTag(101) as well.


Solution

  • I have used IBOutlets as vadian and jrturton advised.

    This is the working code

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("details", forIndexPath: indexPath) as! AccountCell
                    if (indexPath.row == 0) {  let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
                    cell.imageAvtar.userInteractionEnabled = true
                    cell.imageAvtar.addGestureRecognizer(tapGestureRecognizer)
        }
        }
         func imageTapped(img: AnyObject)
            {
                     print("event captured")
                    //your logic comes here
            }