Swift 2 tableview滚动更改数据

时间:2016-03-12 02:44:18

标签: xcode swift tableview

我无法正确加载数据!顶部单元格加载良好然后当我向下滚动并备份一次黑暗的图标时,必须要电话号码被点亮,当它们被触摸时,它们会调用一个随机数字。这很奇怪,因为带有电话号码的其他单元格不会仅改变剩下的等于""。

这是来自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
}

这是tableviewcell.swift文件

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 个答案:

答案 0 :(得分:0)

您看到此行为的原因是您的if缺少else分支,您可以在其中清除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
}

这样可以防止屏幕上滚动的重复使用的按钮显示在缺少电话号码的单元格中。