简体   繁体   English

indexToScrollTo不适用于TableViewCell Swift中的最后一个CollectionView

[英]indexToScrollTo doesnt work with last CollectionView in a TableViewCell Swift

I have made a CollectionView in a TableView for vertical and horizontal scrolling and customisable cells. 我已经在TableView制作了一个CollectionView ,用于垂直和水平滚动以及可自定义的单元格。 This works so far. 到目前为止,该方法有效。

I want it to display specific Cells from the CollectionView at specific IndexPath at the first time opening the app (and if I refresh the page manually). 我希望它在第一次打开应用程序时(如果我手动刷新页面的话)在特定IndexPath的CollectionView中显示特定的单元格。 I get the right IndexPath and it works with every TableViewCell (where the CollectionView is inside), except the last one. 我得到了正确的IndexPath,它与每个TableViewCell (其中的CollectionView都在其中)一起使用,除了最后一个。

Here is my Code: 这是我的代码:

import UIKit
import RealmSwift


class HomeVTwoTableViewCellSmall: UITableViewCell{

//belongs to the center Method
var onceOnly = false
var counterIndexPath = 0

//serves as a translator from ChannelName to the ChannelId
var channelOverview: [String:String] = ["Some: Values"]

//Initiaize the CellChannel Container and Live Programm
var cellChannel: Results<Community>!  
var liveProgramm: Results<Live>?

//Initialize the translated ChannelId
var channelId: String = ""
override func prepareForReuse() {
    channelId = ""
}


var channelTitle = "" {
    didSet {
        let realm = try! Realm()
        //Getting the ChannelId from Dictionary
        self.channelId = self.channelOverview[self.channelTitle]!

        //load data from Realm into variables
        self.cellChannel = realm.objects(Community.self).filter("channelId = \(self.channelId) ").sorted(byKeyPath: "startTime")
        self.liveProgramm = realm.objects(Live.self).filter("channelId = \(self.channelId) ")
        self.collectionView.reloadData()
    }
}
@IBOutlet weak var collectionView: UICollectionView!

override func awakeFromNib() {
    super.awakeFromNib()
    collectionView.delegate = self
    collectionView.dataSource = self
}
}

extension HomeVTwoTableViewCellSmall: UICollectionViewDataSource,UICollectionViewDelegate {

//MARK: Datasource Methods
func numberOfSections(in collectionView: UICollectionView) -> Int
{
    return 1
}

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

//gets the IndexPath to use  
func getLiveIndexPath(){
    var counter = 0
    counterIndexPath = 0
    for i in 0 ..< cellChannel.count
         {
        if (cellChannel[i].communityId != liveProgramm?[0].communityId) {
            counter += 1
        }
        else {
            counterIndexPath = counter
            return
        }
    }
}

//TODO: Center collection view on Live programm
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

    getLiveIndexPath()

    if !onceOnly {
        let indexToScrollTo = IndexPath(item: counterIndexPath, section: 0)
        //Change position of the Live cell by Changing position "at: ..."
        self.collectionView.scrollToItem(at: indexToScrollTo, at: .centeredHorizontally, animated: false)
        onceOnly = true
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellSmall", for: indexPath) as? HomeVTwoCollectionViewCellSmall else
    {
        fatalError("Cell has wrong type")
    }
    let realm = try! Realm()

    let selectedCommunityObject = realm.object(ofType: Community.self, forPrimaryKey: cellChannel[indexPath.row].communityId)!

    //removes the old image and Titel
    cell.imageView.image = UIImage(named: "No Image")
    cell.titleLbl.text = nil

    //inserting the channel specific data
    let url : String = (cellChannel[indexPath.row].pictureId)
    let name : String = (cellChannel[indexPath.row].communityName)
    cell.titleLbl.text = name
    cell.imageView.downloadedFrom(link :"")
    return cell
}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedCommunity = (cellChannel[indexPath.row].communityId)
    let home = HomeViewController()
    home.showCommunityDetail()
}
}

It seems like the in the last CollectionView the "onceOnly" boolean is already true but I don`t get why it works at the beginning but not with the last one. 似乎在上一个CollectionView ,“ onceOnly”布尔值已经是正确的,但我不明白为什么它在开始时起作用,但不适用于最后一个。 It scrolls but not at the right IndexPath 它滚动但不在正确的IndexPath上

Most likely, you're experiencing a problem with a UITableViewCell being reused. 最有可能的是,您遇到了UITableViewCell重用的问题。 What's happening is that you initially dequeue a new cell for channel A, and it's getting setup and shown correctly, including setting onceOnly to true . 发生的事情是,您最初为通道A出队了一个新单元,并且正在设置并正确显示它,包括将onceOnly设置为true Then later on, this cell is getting reused by the tableview and is dequeued to be used for channel B. But in this case, onceOnly and counterIndexPath are still set with the information for A. 然后,稍后,该单元格将被表视图重用,并出队以用于通道B。但是,在这种情况下,仍然使用A的信息设置了onceOnlycounterIndexPath

You're already implementing prepareForReuse . 您已经在实现prepareForReuse You just need to reset additional information there to get what you need. 您只需要在此处重置其他信息即可获得所需的信息。

override func prepareForReuse() {
     channelId = ""
     onceOnly = false
     counterIndexPath = 0
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM