Множественный CollectionView внутри проблемы UITableView Cell (Autoscroll) - PullRequest
0 голосов
/ 22 апреля 2019

У меня есть несколько CollectionView внутри TableView и я хочу реализовать автопрокрутку индивидуально в соответствии с количеством данных в каждом CollectionView

Этот код работает нормально для одного CollectionView

Мой UITableViewCell код здесь

class PromotionalOfferCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource{

    @IBOutlet weak var collVwPromotionalOffer: UICollectionView!

    var x = 1
    var scroll_timer : Timer?

    var data_obj = [PromotionalOfferData]() {
        didSet {
            print(data_obj)
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        if collVwPromotionalOffer != nil{
            self.collVwPromotionalOffer.dataSource = self
            self.collVwPromotionalOffer.delegate = self
        }
    }

    func setTimer() {
        scroll_timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.autoScroll), userInfo: nil, repeats: true)
    }

    @objc func autoScroll() {
        if self.x < self.data_obj.count {
            let indexPath = IndexPath(item: x, section: 0)
            self.collVwPromotionalOffer.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
            self.x = self.x + 1

        } else {
            self.x = 0
            self.collVwPromotionalOffer.scrollToItem(at: IndexPath(item: 0, section: 0), at: .centeredHorizontally, animated: true)
        }
    }

}

// CollectionView Delegate & DataSource

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as? ImageCell

    cell?.imgView.sd_setImage(with:URL(string: data_obj[indexPath.row].image!), placeholderImage: UIImage(named: "cod_logo"), options: [.highPriority]) { (image, error, cashtype, url) in }

    return cell!
}

UITableView Делегат

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

    if tableViewItems.count > 0{
        return self.tableViewItems.count
    }
    return 0
 }

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

        if let Promotional_Item = tableViewItems[indexPath.row] as? [PromotionalOfferData]{

            let cell = tableView.dequeueReusableCell(withIdentifier: "PromotionalOfferCell", for: indexPath) as! PromotionalOfferCell

            cell.data_obj = Promotional_Item
            cell.collVwPromotionalOffer.reloadData()

            if cell.scroll_timer != nil {
                cell.scroll_timer!.invalidate()
                cell.scroll_timer = nil
            }

            if Promotional_Item.count > 1{
                cell.setTimer()
            }
            return cell
        }
    }

Мой вывод такой же

enter image description here

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

В связи с этим объем памяти приложения продолжает увеличиваться, и я уже invalidate таймер

Может кто-нибудь сказать мне, где я не прав?Заранее спасибо

1 Ответ

0 голосов
/ 22 апреля 2019

Привет, Nikunj, вместо того, чтобы делать много таймеров, сделать один таймер и обрабатывать такие действия, как прокрутка в его селекторе, вместо этого для разных ячеек, потому что для каждого таймера ячейки интервал таймера одинаков, вы также можете попробовать сделать это на willdisplay и сделать недействительным в willEndDisplaying ! (хотя я не люблю это многим таймерам). Надеюсь, это помогло!

...