indexToScrollTo不适用于TableViewCell Swift中的最后一个CollectionView(indexToScrollTo doesnt work with last CollectionView in a TableViewCell Swift)
我在
TableView
为垂直和水平滚动和可定制的单元格创建了一个CollectionView
。 这工作到目前为止。我希望它在第一次打开应用程序时(以及如果我手动刷新页面)在特定的IndexPath中显示来自
CollectionView
特定单元格。 我得到了正确的IndexPath,它适用于每个TableViewCell
(CollectionView
所在的位置),除了最后一个。这是我的代码:
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,但我不明白为什么它在开始时运行,而不是在最后一个运行。 它滚动但不在正确的IndexPathI have made a
CollectionView
in aTableView
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 everyTableViewCell
(where theCollectionView
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
最满意答案
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.
相关问答
更多-
除了使用探查器之外,获取所需内容的简单方法如下: public class SomeClass{ public void somePublicMethod() { long startTime = System.currentTimeMillis(); someMethodWhichYouWantToProfile(); long endTime = System.currentTimeMillis(); System.out.printl ...
-
您可以使用秒表类。 Stopwatch sw = Stopwatch.StartNew(); // rest of the code sw.Stop(); Console.WriteLine("Total time (ms): {0}", (long) sw.ElapsedMilliseconds); You can use the stopwatch class. Stopwatch sw = Stopwatch.StartNew(); // rest of the code sw.Stop(); Co ...
-
Haskell函数执行时间(Haskell function execution time)[2023-07-11]
最简单的事情就是做:set +s在ghci :set +s ,然后可以看到运行的任何内容的执行时间以及内存使用情况。 Simplest things is to just do :set +s in ghci, and then you can see the execution time of anything you run, along with memory usage. -
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所指出的那样,如果要对某些代码 ...
-
timeit模块是专门为此目的而设计的。 愚蠢的例子如下 def test(): """Stupid test function""" L = [] for i in range(100): L.append(i) if __name__ == '__main__': from timeit import Timer t = Timer("test()", "from __main__ import test") print t.timeit ...
-
是否可以在没有变量的情况下计算方法执行时间?(Is it possible to calculate method execution time without a variable?)[2024-04-26]
这不是一个简单的答案。 我推断你不希望用不必要的分析代码混淆你的代码,你可能会在以后删除。 在这种情况下,建议使用AOP。 然后,您可以围绕要分析的方法编织方面,这些方面将具有表示“开始”和“结束”变量的变量声明。 This is not a straightforward answer. I'm inferring from the question that you do not wish to clutter your code with unnecessary profiling code, tha ... -
如何从理论上计算出某些方法的执行时间?(How can I calculate the execution time of some method theoretically?)[2022-03-13]
理论上没有办法计算这个。 这取决于许多因素,例如: java版和major / minor / patch版本号。 各种JVM调优参数; 例如堆有多大。 你的硬件平台; CPU,内存大小,甚至主板和时钟速度。 机器上的负载; 即它还在做什么。 CPU散热片上的绒毛量。 严重的是......如果处理器芯片太热,时钟速度可能会降低,主板振荡器时钟速度也会(有点)对温度敏感。 即使您了解所有这些,计算本质上也是Java JIT编译器和硬件执行的取证模拟。 考虑起来太复杂了。 您可以合理地期望在“速度”的理论度量方 ... -
是否有可能在C#中使用属性计算方法的执行时间?(Is it possible to calculate the execution time of a method in C# with attributes?)[2022-10-25]
如果您想编写一些测试代码来分析各种功能或其中的某些部分,您可以使用System.Diagnostics.Stopwatch记录经过的时间。 喜欢这个: public void DoSomething(){ Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); //stuff you want to time stopWatch.Stop(); System.Console.Writeln(String.Format("T ... -
方法在java中的执行时间(Method's execution time in java)[2024-02-12]
为什么不使用分析器,如YourKit或JVisualVM 。 JVisualVM随JDK一起提供。 如果您真的想自己这样做,请使用java.lang.instrument和ASM编写自己的代理。 使用这种方法将逻辑添加到Java方法的序言和结尾是很简单的。 这是一个帮助您入门的链接。 Why don't you just use a profiler, like YourKit or JVisualVM. JVisualVM comes with the JDK. If you really want to ... -
计算程序执行时间(Calculate program execution time)[2024-02-26]
您至少有4种方法可以做到这一点。 (1) 一个起点: #include#include #include int main ( void ) { clock_t start = clock(); system("Test.exe"); printf ("%f\n seconds", ((double)clock() - start) / CLOCKS_PER_SEC); return 0; } ...