在tableView问题

时间:2017-03-10 16:34:15

标签: ios uitableview checkbox swift3 checkmark

我尝试创建一个应用程序来选择/取消选择tableView中的行,所有数据都是从coreData加载的,当我选择一个允许我在coreData中更新它的元素时,反之亦然,

一开始一切正常,我从coreData加载数据,显示tableView中的所有项目,如果需要,在cellForRowAtindexPath中检查行

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell:UITableViewCell? = nil

    let item = (arrayToDisplay[indexPath.section] as Array<NSManagedObject>)[indexPath.row]

    cell = tableView.dequeueReusableCell(withIdentifier: "ShoppingCell")!

    let lblName:UILabel = cell?.viewWithTag(101) as! UILabel

    let attributedString = NSMutableAttributedString(string: (item.value(forKeyPath: "name") as! String?)!)

    if( item.value(forKeyPath: "bought") as! Bool)
    {
        attributedString.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue), range: NSMakeRange(0, attributedString.length))
        attributedString.addAttribute(NSStrikethroughColorAttributeName, value: UIColor.red, range: NSMakeRange(0, attributedString.length))

        cell?.setSelected(true, animated: true) //set checkMark to active/checked status

    }


    lblName.attributedText = attributedString

    return cell!
}

在此之前,我已启用了editStyle,如下所示

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return UITableViewCellEditingStyle(rawValue: 3)!
}

第一次加载视图时,一切正常,当我选中或取消选中CoreData 中的更新值并重新加载我的tableView 时,我从中的coreData和tableView重新加载数据viewDidAppear ,所以每当我在场景之间切换时,都会刷新,使用新数据

当我检查tableView中的项目时,我保存数据,更新我的类数组和reloadData以显示新的更改(包括文本删除线)

这就是问题,每当我重新加载tableView,或在标签之间切换(在TabBar中),并且返回时,检查标记没有正确检查,我无法检查它们,它们看起来像是在不到一秒的时间内检查并取消选中,

我已经检查过我的代码中可能存在一些冲突但是一切都正确,因为对coreData的所有更新操作都已正确完成,

我已经跟踪了ObjC中Maitrayee Ghosh编写的示例项目,你可以通过将[tableView reloadData]添加到didSelectRowAtIndexPath来模拟同样的问题,如下所示

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"user selected %@",[dataArray objectAtIndex:indexPath.row]);

[tableView reloadData];}

那么,如何刷新tableView内容并正确选中检查标记状态,并且能够更改状态,例如Google Keep复选框备注

1 个答案:

答案 0 :(得分:2)

两件事。

cellForRowAt中,您需要else if声明。

if( item.value(forKeyPath: "bought") as! Bool)
{
    attributedString.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue), range: NSMakeRange(0, attributedString.length))
    attributedString.addAttribute(NSStrikethroughColorAttributeName, value: UIColor.red, range: NSMakeRange(0, attributedString.length))

    cell?.setSelected(true, animated: false)
} else {
    cell?.setSelected(false, animated: false)
}

单元格被重用,因此您必须始终处理这两种情况。

didSelectRowAt方法中,您需要更新数据模型,以便cellForRowAt正确呈现单元格。