Один UITableViewCell контролирует другие

Кто-нибудь знает, что здесь происходит? Я настроил UITableView с CollectionViewCells, и каждая из этих ячеек должна работать независимо друг от друга, но когда я прокручиваю одну, она управляет другой ячейкой, которая находится на 3 ячейки ниже нее.

Пытался перенастроить мои UITableViewCells и CollectionViewCells. Но я не совсем уверен, что делать

//TableView controler


import UIKit
import CardsLayout
import CHIPageControl

class eventsFeed: UIViewController, UITableViewDelegate, UITableViewDataSource{


    // Global Variable
    var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        tableView = UITableView(frame: CGRect(x: self.view.bounds.minX, y: self.view.bounds.minY+UIApplication.shared.statusBarFrame.height, width: self.view.bounds.width, height: self.view.bounds.height))

        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        self.view.addSubview(tableView)

        tableView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
        cell.backgroundColor = UIColor.white
        cell.selectionStyle = .none
        return cell
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        return 430.0;//Choose your custom row height
    }



}


//CollectionViewCell for TableView

import UIKit
import CardsLayout

class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {



    var collectionView: UICollectionView!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)


        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal

        collectionView = UICollectionView(frame: CGRect(x: 0, y:0, width: UIScreen.main.bounds.width, height: 410.0), collectionViewLayout: layout)
        collectionView.center = CGPoint(x: 187.5, y: 180)
        collectionView.collectionViewLayout = CardsCollectionViewLayout()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
        collectionView.backgroundColor = UIColor.white

        self.addSubview(collectionView)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    var colors: [UIColor]  = [
        UIColor(red: 237, green: 37, blue: 78),
        UIColor(red: 249, green: 220, blue: 92),
        UIColor.blue,
        UIColor(red: 1, green: 25, blue: 54),
        UIColor(red: 255, green: 184, blue: 209),
        UIColor(red: 237, green: 37, blue: 78),
        UIColor(red: 249, green: 220, blue: 92)
        ]

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
        cell.layer.cornerRadius = 12.0
        cell.backgroundColor = colors[indexPath.row]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return colors.count
    }
}

Видео выпуска: https://www.reddit.com/r/iOSProgramming/comments/btcok4/does_anyone_know_whats_happening_here_ive/

Стоит ли изучать 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 называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
0
47
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

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

Сохраните где-нибудь текущее состояние для каждой ячейки представления таблицы (например, в структурах массива), а затем настройте ячейку на основе этого состояния в методе cellForRowAt делегата.

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