1

I am having trouble getting the data to load correctly! The top cells load well then when I scroll down and back up the once dark icons that had to phone number are lit and when they are touched they call a random number. This is odd, as the other cells with a phone number do not change only the ones that are left equalling "".

This is from the ViewController.swift

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell

    let contact = contactList[indexPath.row]

    cell.name.text = "\(contact.name)"

    cell.id.text = "\(phoneFormat(contact.callPhone))"

    if contact.callPhone != "" {

        cell.callButton.setImage(UIImage(named: "phone.png"), forState: UIControlState.Normal)

        cell.callButton.userInteractionEnabled = true

        cell.callButton.tag = indexPath.row

        cell.callButton.addTarget(self, action: "call:", forControlEvents: .TouchUpInside)

    }

   /* if contact.smsPhone != nil {

        cell.smsButton.setImage(UIImage(named: "chat.png"), forState: UIControlState.Normal)

        cell.smsButton.userInteractionEnabled = true

        cell.smsButton.tag = indexPath.row
    }

    if contact.email != nil {

        cell.emailButton.setImage(UIImage(named: "email.png"), forState: UIControlState.Normal)

        cell.emailButton.userInteractionEnabled = true

        cell.emailButton.tag = indexPath.row

    }*/

    return cell
}

this is the tableviewcell.swift file

class TableViewCell: UITableViewCell {

@IBOutlet var name: UILabel!

@IBOutlet var id: UILabel!

@IBOutlet var callButton: UIButton!

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
}}

1 Answers1

0

The reason that you see this behavior is that your if is missing an else branch, in which you clear out the content of visuals being set in the if:

if contact.callPhone != "" {
    cell.callButton.setImage(UIImage(named: "phone.png"), forState: UIControlState.Normal)
    cell.callButton.userInteractionEnabled = true
    cell.callButton.tag = indexPath.row
    cell.callButton.addTarget(self, action: "call:", forControlEvents: .TouchUpInside)
} else {
    cell.callButton.setImage(nil, forState: UIControlState.Normal)
    cell.callButton.userInteractionEnabled = false
    cell.callButton.tag = 0
    cell.callButton.hidden = true
}

This would prevent buttons from reused cells scrolled off the screen from showing up in cells for which the phone number is missing.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523