onkar
onkar

Reputation: 4547

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.

Upvotes: 0

Views: 675

Answers (3)

onkar
onkar

Reputation: 4547

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
        }

Upvotes: 0

Ketan Parmar
Ketan Parmar

Reputation: 27448

Try,

cell.viewWithTag(101) or self.view.viewWithTag(101) if tag is unique(i.e. if you are not using this tag at other place).

Second thing you have to add gesture recognizer to capture event on it. How you come to know that it's returning nil ? It may not return nil. You are making another mistake. Make sure that no_image_available.jpg is properly available in project!

Another thing is make sure that you have set tag properly.

Upvotes: 0

Er. Khatri
Er. Khatri

Reputation: 1414

check your imageView's tag in interface builder or storyboard if it is 0 make it 101 and retry..

you can also check

for subView in cell.contentView.subView {
    print("subView tag --> \(subView.tag)!")
}

try this in your cellForRowAtIndexPath

Upvotes: 0

Related Questions