Цвет ячейки TableView сбрасывается после прокрутки

Я использую swift для создания одного из своих первых приложений, я хочу иметь возможность изменять цвета определенных ячеек в зависимости от погоды или нет, которые были выбраны и добавлены в selectedHobbies. Всякий раз, когда это делается, кажется, что это работает, но когда я прокручиваю вниз и назад, кажется, что ячейки сбрасываются до исходного цвета.

import UIKit

var selectedHobbies : [String] = [] //Hold a global value of the 
selected hobbies
 var numberSelected:Int = 0 //Hold the number of selected hobbies


class TableViewController: UITableViewController, 
UISearchResultsUpdating {





var filteredHobbies = [String]() //The hobbies filted by the search bar
var searchController = UISearchController()
var resultController = UITableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.searchController = UISearchController(searchResultsController: resultController)
        tableView.tableHeaderView = self.searchController.searchBar

        self.searchController.searchResultsUpdater = self

        self.resultController.tableView.delegate = self
        self.resultController.tableView.dataSource = self



    }
    //updates search results according to what is in the search bar, filters hobbies out that dont contain the same string of text
    func updateSearchResults(for searchController: UISearchController) {
        self.filteredHobbies = hobbies.filter({ (hobbies: String) -> Bool in

            if hobbies.contains(searchController.searchBar.text!)
            {
                return true
            }
            else
            {
                return false
            }

        })

        self.resultController.tableView.reloadData()
    }




   // number of
    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1

    }
//swipe actions for table view
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            let important = importantAction(at: indexPath)
            return UISwipeActionsConfiguration(actions: [important])
    }
//takes the hobby according to the searched hobbies (if they are filtered)
func importantAction(at IndexPath: IndexPath) -> UIContextualAction {
    var hobby = ""
    if searchController.searchBar.text! == "" {
        hobby = hobbies[IndexPath.row]

    } else {
        hobby = filteredHobbies[IndexPath.row]
    }

    let action = UIContextualAction(style: .normal, title: "Important") { (action, view, completion) in
        completion(true)
    }
    // wont add hobbies otherwise
    if selectedHobbies.contains(hobby){
        action.title = "Add Hobby"
        action.backgroundColor = .gray

        print(selectedHobbies)
        return action

    }else {
    // adds hobbies if they arent in the array
        selectedHobbies.append(hobby)
        action.title = "Add Hobby"
        tableView.cellForRow(at: IndexPath)?.backgroundColor = UIColor.white
        action.backgroundColor = .green
        numberSelected += 1
        if numberSelected >= 10 {
            performSegue(withIdentifier: "segue1", sender: nil)
            print(selectedHobbies)
        }
        print(selectedHobbies)
        return action
    }
}
func removeAction(at IndexPath: IndexPath) -> UIContextualAction {
    var hobby = ""
    if searchController.searchBar.text! == "" {
        hobby = hobbies[IndexPath.row]
    } else {
        hobby = filteredHobbies[IndexPath.row]
    }

    let action = UIContextualAction(style: .normal, title: "Important") { (action, view, completion) in
        completion(true)
    }
    if selectedHobbies.contains(hobby){ //removes hobby if in selected hobbies

        selectedHobbies = selectedHobbies.filter{$0 != hobby}
        action.title = "Remove Hobby"
        action.backgroundColor = .red
        numberSelected -= 1

        print(selectedHobbies)
        return action
    }else {
        action.title = "Remove Hobby"
        action.backgroundColor = .gray
        print(selectedHobbies)
        return action
    }
}

override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let remove = removeAction(at: indexPath)
    return UISwipeActionsConfiguration(actions: [remove])
}

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


        if tableView == resultController.tableView
        {
            return self.filteredHobbies.count
        }
        else
        {
            return self.hobbies.count
        }

    }



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

        let cell = UITableViewCell()


        if tableView == resultController.tableView
        {

            cell.textLabel?.text = self.filteredHobbies [indexPath.row]
        }
        else
        {
            cell.backgroundColor = UIColor.cyan
            cell.textLabel?.text = self.hobbies[indexPath.row]
        }



        return cell




    }


 }

Любая помощь приветствуется, спасибо

Вам нужно установить цвет в cellForRowAt.

rmaddy 27.05.2018 02:30
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
1
1
57
1

Ответы 1

В вашем cellForRowAt selectedHobbies проверьте, находится ли объект в selectedHobbies и раскрасьте ячейку в соответствии с этим

   if selectedHobbies.contains(hobby){

     }else{

   }

Я не совсем понимаю, что вы имеете в виду, куда мне вставить данные строки кода?

techgeek14 27.05.2018 21:48

На cellForRowAt

Abdelahad Darwish 27.05.2018 21:50

Где я могу изменить cellForRowAt. Извините, я новичок в программировании в целом.

techgeek14 28.05.2018 14:11

переопределить func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

Abdelahad Darwish 28.05.2018 14:11

Как это? переопределить func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {if selectedHobbies.contains (hobby) {cell.backgroundColor = UIColor.yellow} else {cell.backgroundColor = UIColor.clear} return cell}

techgeek14 28.05.2018 14:44

Другие вопросы по теме