sguruapp@gmail.com
facebook vk instagram Телеграм youtube

Добавить товар в избранное tableView и выделить из всех товаров только те, которые находятся в избранном - цветом (выделение ячеек, пример работы с выделением ячеек) - Swift 5


class MainTableViewController: UITableViewController {

// Название категорий (секций)
let categories = ["One", "Two", "Five"]

// Данные для каждой секции
let globalData = [
// Секция 0
["Goods 1", "Goods 2", "Goods 3", "Goods 4"],
// Секция 1
["Audio 1", "Audio 2"],
// Секция 2
["iPhone X", "iPad Pro", "Mac mini", "iMac", "iPad", "iPhone XR", "iPod"]
]

// Те товары, которые добавлены в избранное
let favArray = ["iPad Pro", "Goods 3"]


// Работа с таблицей
override func numberOfSections(in tableView: UITableView) -> Int {
return globalData.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return globalData[section].count
}

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

cell.textLabel?.text = globalData[indexPath.section][indexPath.row]

if favArray.contains(where: {$0 == globalData[indexPath.section][indexPath.row]}) == true {
cell.backgroundColor = .yellow

} else {
cell.backgroundColor = .white
}

return cell
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return categories[section]
}

}

Возврат к списку

обучись профессии будущего

Хочешь стать успешным разработчиком
приложений? Тогда добро пожаловать к нам.

обучись профессии будущего