【问题标题】:How to delete row at dynamic tableView Swift如何在动态 tableView Swift 中删除行
【发布时间】:2018-10-26 23:42:59
【问题描述】:

这是我的问题。我有一个用户数组,我正在检查用户电话号码是否在地址簿中,我想在 tableView 中显示用户。

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return users.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell

    let user = users[indexPath.row]
    let contact = searchForContactUsingPhoneNumber(phoneNumber: user.phoneNumber!)
    if contact == true {
        cell.textLabel?.text = user.name
        cell.detailTextLabel?.text = user.phoneNumber
        cell.backgroundColor = UIColor(r: 35, g: 35, b: 35)
        cell.textLabel?.textColor = UIColor.white
        cell.detailTextLabel?.textColor = UIColor.white

        if let profileImageUrl = user.profileImageUrl {
        cell.profileImageView.loadImageUsingCacheWithUrlString(profileImageUrl)

        } else {
            tableView.deleteRows(at: [indexPath], with: .automatic)
            tableView.reloadData()
        }
    }
    return cell
}

这就是我所拥有的。如果电话号码不在通讯录中,它会删除用户行,但会留下白行。

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    您不应在 cellForRowAt 中修改表格中的单元格数量,或重新加载表格视图。最好先过滤 users 数组,然后使用过滤后的结果数组作为数据源。

    有点像

    let usersWithPhoneNumbers = users.filter { $0.profileImageUrl != nil && searchForContactUsingPhoneNumber(phoneNumber: $0.phoneNumber!) }
    

    然后在 numberOfRows 和 cellForRow 方法中使用 usersWithPhoneNumbers 数组。

    【讨论】:

    • 同意,首先删除根本不应该显示的行并不是过滤列表的好方法。事先做,使用过滤列表作为 1:1 数据源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多