首页 \ 问答 \ indexToScrollTo不适用于TableViewCell Swift中的最后一个CollectionView(indexToScrollTo doesnt work with last CollectionView in a TableViewCell Swift)

indexToScrollTo不适用于TableViewCell Swift中的最后一个CollectionView(indexToScrollTo doesnt work with last CollectionView in a TableViewCell Swift)

我在TableView为垂直和水平滚动和可定制的单元格创建了一个CollectionView 。 这工作到目前为止。

我希望它在第一次打开应用程序时(以及如果我手动刷新页面)在特定的IndexPath中显示来自CollectionView特定单元格。 我得到了正确的IndexPath,它适用于每个TableViewCellCollectionView所在的位置),除了最后一个。

这是我的代码:

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()
}
}

它看起来像在最后一个CollectionView ,“onceOnly”布尔值已经是true,但我不明白为什么它在开始时运行,而不是在最后一个运行。 它滚动但不在正确的IndexPath


I have made a CollectionView in a TableView for vertical and horizontal scrolling and customisable cells. 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). I get the right IndexPath and it works with every TableViewCell (where the CollectionView is inside), except the last one.

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. It scrolls but not at the right IndexPath


原文:https://stackoverflow.com/questions/45463975
更新时间:2023-05-22 18:05

最满意答案

Stopwatch是为此设计的,是测量.NET中时间执行的最佳方法之一。

var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

不要使用DateTimes来测量.NET中的执行时间。


更新:

正如在评论部分中的@系列1所指出的那样,如果要对某些代码的执行进行真正的精确测量,则必须使用内置于操作系统中的性能计数器。 following answer包含一个很好的概述。


Stopwatch is designed for this purpose and is one of the best ways to measure time execution in .NET.

var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

Do not use DateTime to measure time execution in .NET.


UPDATE:

As pointed out by @series0ne in the comments section: If you want a real precise measurement of the execution of some code, you will have to use the performance counters that's built into the operating system. The following answer contains a nice overview.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)