简体   繁体   中英

TableView rearranging / creating blank cells when scrolling. Swift

Alright, so I'm creating this view where I bring all the contacts on the phone, and I'm simply adding them in an array and looping trough that array in order to create cells in my table view. The problem is, when I scroll, the cell content changes on index or simply disappears from the table. I'm creating my table and populating it like so:

public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return Int(numberofContacts)        
}

var i = 0

public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    print(i)
    let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

    if(i < numberofContacts){
        cell.textLabel?.text = results[i].givenName + " " + results[i].familyName

    }
    i++

    return cell

}

Where the vars results and numberofContacts are being retrieved by the CNContactStore() , that part works fine. The table gets populated with all the contacts and you can scroll them down perfectly, but once the cell get's scrolled out of the screen, the value when you scroll back gets reassigned.

I'm also adding the feature of when you click a contact name you call their first assigned number like so:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {

    if results[indexPath.row].isKeyAvailable(CNContactPhoneNumbersKey){
        let selected = (results[indexPath.row].phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as! String

        let urlPhone = NSURL(string: "tel://\(selected)")

        UIApplication.sharedApplication().openURL(urlPhone!)

    }

}

Please help, I have no idea where I'm messing this. Thank you.

You should be doing it this way:

public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return Int(numberofContacts)        
}

public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

    cell.textLabel?.text = results[indexPath.row].givenName + " " + results[indexPath.row].familyName
    return cell
}

Your cells are being reused, so if you rely on your i var you are going to end up increasing it's value beyond numberofContacts and that's what is giving you the empty cells.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM