【问题标题】:TableView rearranging / creating blank cells when scrolling. Swift滚动时 TableView 重新排列/创建空白单元格。迅速
【发布时间】:2016-02-02 19:49:23
【问题描述】:

好的,所以我正在创建这个视图,将所有联系人带到手机上,我只是将它们添加到一个数组中并在该数组中循环,以便在我的表格视图中创建单元格。问题是,当我滚动时,单元格内容会在索引上发生变化,或者只是从表格中消失。我正在创建我的表格并像这样填充它:

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

}

CNContactStore() 正在检索变量 resultsnumberofContacts 时,该部分工作正常。表格中填充了所有联系人,您可以完美地向下滚动它们,但是一旦单元格滚动出屏幕,您向后滚动时的值将被重新分配。

我还添加了一个功能,当您单击联系人姓名时,您会拨打他们的第一个分配号码,如下所示:

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!)

    }

}

请帮忙,我不知道我在哪里搞砸了。谢谢。

【问题讨论】:

    标签: ios xcode swift uitableview swift2


    【解决方案1】:

    你应该这样做:

    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
    }
    

    您的单元格正在被重复使用,因此如果您依赖您的 i var,您最终会将其价值提高到超过 numberofContacts,这就是给您空单元格的原因。

    【讨论】:

    • 谢谢。这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2021-05-01
    • 2020-08-01
    • 1970-01-01
    相关资源
    最近更新 更多