2017-11-07 1 views
0

UIViewControllerの中にUITableViewがあり、ユーザーがアプリをリロードするときに、NSUserDefaultを使用して事前に選択したセルユーザーがチェックマークを表示するようにaccessoryTypeのステータスを保存しようとします。 。しかし、私が直面している問題は、セルのデータがユーザーのデフォルトのデータと等しいかどうかをチェックすると、選択されなかったセルの中にもチェックマークが表示されていることです。ここ特定のUITableViewCellのcheckMarkステータスを保存するには

は私のコードです:あなたはセルをデキューしているので、

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = newCategoriesTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
    cell.backgroundColor = colorArray[indexPath.row] 
    let entry: Categories 
    if isFiltering() { 
     entry = filteredCategories[indexPath.row] 
    } else { 
     entry = categoryTitles[indexPath.row] 
    } 

    cell.selectionStyle = .none 

    cell.textLabel?.text = entry.name 
    cell.detailTextLabel?.text = entry.description 

    let defaults = UserDefaults.standard 
    if let userCategortList = defaults.object(forKey: "userCategoryList") as? [String]{ 
      for category in userCategortList{ 
       if(cell.textLabel?.text == category){ 
        cell.accessoryType = .checkmark 
        break 
       } 
      } 
     } 

    return cell 
} 

答えて

0

これはおそらく、細胞の再利用の問題です。チェックマークに設定されていない場合は、cell.accessoryType = .noneを設定する必要があります。

+1

これは、カスタムセル(存在する場合)の 'prepareForReuse'メソッドでよく行われることになるでしょう。 – JMFR

0

以下のスニペットで試してください。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
      let cell = newCategoriesTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
      cell.backgroundColor = colorArray[indexPath.row] 
      let entry: Categories 
      if isFiltering() { 
       entry = filteredCategories[indexPath.row] 
      } else { 
       entry = categoryTitles[indexPath.row] 
      } 

      cell.selectionStyle = .none 

      cell.textLabel?.text = entry.name 
      cell.detailTextLabel?.text = entry.description 

      let defaults = UserDefaults.standard 
      if let entry.name == (defaults.object(forKey: "userCategoryList") as? [String]){ 
        cell.accessoryType = .checkmark      
       } 
      else{ 
        cell.accessoryType = .none 
       } 

      return cell 
     } 

entry.nameをユーザーのデフォルト値に保存します。

関連する問題